Saturday, August 11, 2012

Serialize Class Object using Triple DES algorithm

DES encryption is not safe and although the code is a little old check out the vector and key in the code below, Triple DES is much safe. The crux of encryption is predictiblity and creating vector and key randon will make things more unpredictable and in this case user 192 bits for it.

Referred following
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters;
using System.Runtime.Serialization.Formatters.Binary;
using System.Security.Cryptography;

Initialization
TripleDESCryptoServiceProvider cryptic = new TripleDESCryptoServiceProvider();
IFormatter formatter = new BinaryFormatter();
Stream stream = null;

Serialize
stream = new FileStream("MyConfig.txt", FileMode.Create, FileAccess.Write, FileShare.None);
using (CryptoStream cs = new CryptoStream(stream, new TripleDESCryptoServiceProvider().CreateEncryptor(cryptic.Key, cryptic.IV), CryptoStreamMode.Write))
{
    formatter.Serialize(cs, testClassObject);
    cs.FlushFinalBlock();
}
stream.Close();

Deserialize
stream = new FileStream("MyConfig.txt", FileMode.Open, FileAccess.Read, FileShare.None);
using (CryptoStream cs = new CryptoStream(stream, new TripleDESCryptoServiceProvider().CreateEncryptor(cryptic.Key, cryptic.IV), CryptoStreamMode.Read))
{
    testClassObject = (TestClass)formatter.Deserialize(cs);
}
stream.Close();

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

No comments:

Post a Comment