Thursday, July 5, 2012

Serialize Class Object using DES algorithm

There is a specific requirement I have in my present implementation. Need to maintain a data store in the application in which some of the data needed to be stored and fetched whenever application launched again. To achieve created class in Singleton and made it serialized. Some of the objects in the class are not serialized.
I will be posting the implementation of Singleton class object later. Following is the implementation where class object has been serialized and de-serialized. I also have a requirement to encrypt the data.

To achieve this used DESCryptoServiceProvider and CryptoStream.
"TestStoreObj" is the class object which is in Singleton and I am serializing it here.

Note :- You can use Triple DES for it but it will impact performance due to multiple iteration of encryption.

Implementation:

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

Initialization
DESCryptoServiceProvider cryptic = new DESCryptoServiceProvider();
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 DESCryptoServiceProvider().CreateEncryptor(cryptic.Key, cryptic.IV), CryptoStreamMode.Write))
{
    formatter.Serialize(cs, TestStoreObj);
    cs.FlushFinalBlock();
}
stream.Close();

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

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

No comments:

Post a Comment