如何加密序列化的XML并存储在注册表中

时间:2010-07-06 17:48:12

标签: c# encryption xml-serialization registry

我正在尝试加密序列化的XML文档并将其存储在注册表中。我想知道如何做到这一点?我可以通过将XMLdoc转换为字节数组来在注册表中存储非序列化的XML文档,但我不确定如何为序列化的XML执行此操作。

我的XML序列化示例:

using System.Xml.Serialization;

namespace Common.XMLs
{
    [XmlRoot("MyDatabase")]
    public class MyDatabase
    {
        [XmlElement("Item")]
        public Items[] Item; 
    }

    public class Items
    {
        [XmlElement()]
        public string Number;
        [XmlElement()]
        public string Revision;
        [XmlElement()]
        public string DateTimeSet;
        [XmlElement()]
        public string User;
    }
}

由此,我将使用XML序列化和反序列化来读取和写入文件,除了这不是文件,我需要加密它并将其存储在注册表中。

2 个答案:

答案 0 :(得分:0)

由于您拥有XML文档的字节数组,因此非常简单:

public static byte[] EncryptBytes(byte[] toEncrypt, byte[] key, byte[] IV)
{
    using (RijndaelManaged RMCrypto = new RijndaelManaged())
    using (MemoryStream ms = new MemoryStream())
    using (ICryptoTransform encryptor = RMCrypto.CreateEncryptor(key, IV))
    using (CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
    {
        cs.Write(toEncrypt, 0, toEncrypt.Length);
        cs.FlushFinalBlock();
        return ms.ToArray();
    }
}

public static byte[] DecryptBytes(byte[] toDecrypt, byte[] key, byte[] IV)
{
    using (RijndaelManaged RMCrypto = new RijndaelManaged())
    using (MemoryStream ms = new MemoryStream())
    using (ICryptoTransform decryptor = RMCrypto.CreateDecryptor(key, IV))
    using (CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Write))
    {
        cs.Write(toDecrypt, 0, toDecrypt.Length);
        cs.FlushFinalBlock();
        return ms.ToArray();
    }
}

答案 1 :(得分:0)

我喜欢将企业库用于此类加密方案,它具有很多实用性,并且会占用大量代码。具体来说,您可以使用对称加密算法,该算法将吐出一个Base64字符串,然后您可以将其存储在注册表中。

点击此链接:http://msdn.microsoft.com/en-us/library/ff664686(v=PandP.50).aspx