Tuesday, April 5, 2011

How to Encrypt and decrypt xml files in C#

In this post we are going to encrypt and decrypt xml files using RijndaelManaged class.
this class will be in System.Security.Cryptography namespace.
The System.Security.Cryptography namespace provides cryptographic services, including secure encoding and decoding of data.
Encrypt

    public static void EncryptAndSerialize(Object obj)
    {
        UnicodeEncoding aUE = new UnicodeEncoding();
        byte[] key = aUE.GetBytes("password");
        RijndaelManaged RMCrypto = new RijndaelManaged();
        using (FileStream fs = File.Open(@"D:\Sample.xml", FileMode.Create))
        {
        using (CryptoStream cs = new CryptoStream(fs, RMCrypto.CreateEncryptor(key,   key), CryptoStreamMode.Write))
            {
                XmlSerializer xmlser = new XmlSerializer(obj.GetType());
                xmlser.Serialize(cs, obj);
            }
            fs.Close();
    }

Decrypt
public static DataSet DecryptAndDeserialize(string filename)
    {
        DataSet ds = new DataSet();
        FileStream aFileStream = new FileStream(filename, FileMode.Open);
        StreamReader aStreamReader = new StreamReader(aFileStream);
        UnicodeEncoding aUE = new UnicodeEncoding();
        byte[] key = aUE.GetBytes("password");
        RijndaelManaged RMCrypto = new RijndaelManaged();
        CryptoStream aCryptoStream = new CryptoStream(aFileStream, RMCrypto.CreateDecryptor(key, key),     CryptoStreamMode.Read);

        //Restore the data set to memory.
        ds.ReadXml(aCryptoStream);
        aStreamReader.Close();
        aFileStream.Close();
       return ds;
    }

For more info Refer following links

http://msdn.microsoft.com/en-us/library/system.security.cryptography.aspx

http://msdn.microsoft.com/en-us/library/system.security.cryptography.cryptostream.aspx

1 comment: