.NET中加密XML文档,并在内存中解密

来源:互联网 发布:淘宝买的衣服没有吊牌 编辑:程序博客网 时间:2024/05/20 00:37

        加密XML文档的重要性不用说,解密时也希望不要写在硬盘中而是直接在内存中解密成DataSet进行操作,加密算法使用.NET提供的System.Security.dll,目录为:C:\Program Files\Referenc Assemblies\Microsoft\Framework\.NETFramework\v4.0\Profile\Client\,命名空间为System.Security、System.Security.Cryptography及System.Security.Cryptography.Xml,为AES的Rijndael算法。

/// <summary>/// 对相应XML文件解密(直接将密文解密到内存的XmlDocument对象中,不写入文件)。/// </summary>/// <param name="srcPath">要解密的XML密文文档的路径。</param>/// <param name="privateKey">加密的私钥(为32位=数字或字母16个=汉字8个)。</param>/// <returns>解密的明文的XmlDocument对象。</returns>public static XmlDocument DecryptInMemory(string srcPath, string privateKey){    RijndaelManaged key = new RijndaelManaged();    //设置密钥:key为32位=数字或字母16个=汉字8个    byte[] byteKey = Encoding.Unicode.GetBytes(privateKey);    if (byteKey.Count<byte>() == 16)    {        key.Key = byteKey;    }    else    {        key.Key = Encoding.Unicode.GetBytes(defaultPrivateKey);    }    XmlDocument xmlDoc = new XmlDocument();    xmlDoc.PreserveWhitespace = true;    xmlDoc.Load(srcPath); //加载要解密的xml文件    Decrypt(xmlDoc, key);    if (key != null)    {        key.Clear();    }    //xmlDoc.Save(srcPath); //生成解密后的xml文件    return xmlDoc;}/// <summary>/// XML解密。/// </summary>/// <param name="doc">要解密的XmlDocument对象,即XML文档。</param>/// <param name="alg">对称加密算法的密钥。</param>private static void Decrypt(XmlDocument doc, SymmetricAlgorithm alg){    XmlElement encryptedElement = doc.GetElementsByTagName("EncryptedData")[0] as XmlElement;    EncryptedData edElement = new EncryptedData();    edElement.LoadXml(encryptedElement);    EncryptedXml exml = new EncryptedXml();    byte[] rgbOutput = exml.DecryptData(edElement, alg);    exml.ReplaceData(encryptedElement, rgbOutput);}




原创粉丝点击