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
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
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;
}
http://msdn.microsoft.com/en-us/library/system.security.cryptography.aspx
http://msdn.microsoft.com/en-us/library/system.security.cryptography.cryptostream.aspx
for 1024 bit encryption http://aspnettutorialonline.blogspot.com/2012/05/encryption-and-decryption-in-aspnet.html
ReplyDelete