...Technology Simplified

Tuesday, June 19, 2012

Rijndael Algorithm for Encryption and Decryption

No comments :

I have implemented a sample code to implement encryption and decryption of string using Rijndael Algorithm

 protected void Page_Load(object sender, EventArgs e)
{
string clearData = "Hello, World!";
string key = "s@1tValue";
byte[] b = Encrypt(clearData, key);
Response.Write("Encrypted String: " + Convert.ToBase64String(b));
Response.Write("--------------------------------------------------------------");
Response.Write("Decrypted String: " + Encoding.UTF8.GetString(Decrypt(b, key)));
}

public static byte[] Encrypt(string iclearData, string key)
{
try
{
byte[] clearData = Encoding.ASCII.GetBytes(iclearData);
var salt = new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 };
var pdb = new PasswordDeriveBytes(key, salt);
MemoryStream ms = new MemoryStream();
var alg = Rijndael.Create();
alg.Key = pdb.GetBytes(32);
alg.IV = pdb.GetBytes(16);
CryptoStream cryptoStream = new CryptoStream(ms,alg.CreateEncryptor(),CryptoStreamMode.Write);
cryptoStream.Write(clearData, 0, clearData.Length);
cryptoStream.FlushFinalBlock();
byte[] cipherTextBytes = ms.ToArray();
ms.Close();
cryptoStream.Close();
return cipherTextBytes;
}
catch (Exception)
{
throw new Exception("Encryption Failed");
}
}

public static byte[] Decrypt(byte[] cipherData, string key)
{
try
{
var salt = new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 };
var pdb = new PasswordDeriveBytes(key, salt);
var alg = Rijndael.Create();
alg.Key = pdb.GetBytes(32);
alg.IV = pdb.GetBytes(16);
MemoryStream ms = new MemoryStream(cipherData);
CryptoStream cryptoStream = new CryptoStream(ms,alg.CreateDecryptor(),CryptoStreamMode.Read);
byte[] plainTextBytes = new byte[cipherData.Length];
int decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
ms.Close();
cryptoStream.Close();
return plainTextBytes;
}
catch (Exception)
{
throw new Exception("Decryption Failed");
}
}

No comments :

Post a Comment