开发者

How to encrypt a serialized XML and store in registry

I'm trying to encrypt a serialized XML document and store it in the registry. I was wondering on how to accomplish that? I am able to store a non-serialized XML document in the registry by converting the XMLdoc to a byte array, but I'm not sure on how to do it for a serialized XML.

My XML serialization example:

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()]开发者_JAVA技巧
        public string User;
    }
}

From this, I would use the XML serialization and deserialization to read and write the file, except that this isn't going to a file, I need to encrypt it and store it in the registry.


I like to use the Enterprise Library for cryptographic scenarios such as this, it has a lot of utility to it and takes a lot of the overhead out of your code. Specifically you can use a symmetric encryption algorithm which will spit out a Base64 string that you can then store in the registry.

Check out this link: http://msdn.microsoft.com/en-us/library/ff664686(v=PandP.50).aspx


Since you have the byte array of the XML document, it's quite easy:

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();
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜