C# XML 加密解密

步骤 1: 生成RSA密钥

首先,我们需要生成一个RSA密钥对,用于加密和解密。

using System;
using System.Security.Cryptography;
using System.Xml;

public class XmlEncryptionExample
{
    public static RSAParameters publicKey;
    public static RSAParameters privateKey;

    static void Main()
    {
        GenerateKeys();
        string originalXml = "<root><child>Secret Data</child></root>";

        // 加密
        string encryptedXml = EncryptXml(originalXml);
        Console.WriteLine("Encrypted XML:");
        Console.WriteLine(encryptedXml);

        // 解密
        string decryptedXml = DecryptXml(encryptedXml);
        Console.WriteLine("\nDecrypted XML:");
        Console.WriteLine(decryptedXml);
    }

    public static void GenerateKeys()
    {
        using (var rsa = new RSACryptoServiceProvider(2048))
        {
            publicKey = rsa.ExportParameters(false);
            privateKey = rsa.ExportParameters(true);
        }
    }
}

步骤 2: 加密XML

然后,我们可以创建一个函数来加密XML文档。

public static string EncryptXml(string xmlContent)
{
    var xmlDoc = new XmlDocument();
    xmlDoc.PreserveWhitespace = true;
    xmlDoc.LoadXml(xmlContent);

    var encryptedXml = new EncryptedXml(xmlDoc);

    var encryptedData = new EncryptedData
    {
        Type = EncryptedXml.XmlEncElementUrl,
        EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncRSA15Url)
    };

    var encryptedElement = encryptedXml.Encrypt(xmlDoc.DocumentElement, publicKey);
    encryptedData.CipherData.CipherValue = encryptedElement.CipherValue;

    var encryptedXmlDocument = new XmlDocument();
    encryptedXmlDocument.PreserveWhitespace = true;
    encryptedXmlDocument.AppendChild(encryptedXmlDocument.CreateElement("root"));
    encryptedXmlDocument.DocumentElement.AppendChild(encryptedXmlDocument.ImportNode(encryptedData.GetXml(), true));

    return encryptedXmlDocument.InnerXml;
}

步骤 3: 解密XML

最后,我们需要一个函数来解密加密后的XML。

public static string DecryptXml(string encryptedXmlContent)
{
    var encryptedXmlDocument = new XmlDocument();
    encryptedXmlDocument.LoadXml(encryptedXmlContent);

    var encryptedXml = new EncryptedXml(encryptedXmlDocument);
    encryptedXml.AddKeyNameMapping("RSAKey", privateKey);

    var encryptedData = new EncryptedData();
    encryptedData.LoadXml(encryptedXmlDocument.DocumentElement);

    var decryptedXmlElement = encryptedXml.DecryptData(encryptedData, privateKey);
    var xmlDoc = new XmlDocument();
    xmlDoc.PreserveWhitespace = true;
    xmlDoc.LoadXml(decryptedXmlElement);

    return xmlDoc.InnerXml;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值