views:

57

answers:

2

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()]
        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.

A: 

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();
    }
}
Jesse C. Slicer
That's what I have for the XML Document, but I'm looking to encrypt and store Serialized XMLs, not standard XML documents.
dangerisgo
Please explain what a "Serialized XML" is... If you have a byte array, this will encrypt it and decrypt it.
Jesse C. Slicer
Using created classes to create/edit the XML document rather than using generic System.Xml classes
dangerisgo
I'm still unsure what that means. Can you post some of that code into your question? Thanks.
Jesse C. Slicer
A: 

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

Coding Gorilla