Pages

Search

Saturday, January 10, 2009

Password encryption .NET?

User login credentials (Especially password) need to be encrypted such that even data base administrator who handles data base cannot find the exact password as it is stored in encrypted format.
System.Security.Cryptography provided by .NET frame work helps to encrypt/decrypt text, provided with a static key base lined or hard coded to do so.
I am considering below as my static key to encrypt/decrypt text
string Key = "3&hj;@asdj^";
For encrypting
public string EncryptMessage(string plainMessage)
{
TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider();
des.IV = new byte[8];
PasswordDeriveBytes pdb = new PasswordDeriveBytes(Key, new byte[0]);
des.Key = pdb.CryptDeriveKey("RC2", "MD5", 128, new byte[8]);
MemoryStream ms = new MemoryStream(plainMessage.Length * 2);
CryptoStream encStream = new CryptoStream(ms, des.CreateEncryptor(),
CryptoStreamMode.Write);
byte[] plainBytes = Encoding.UTF8.GetBytes(plainMessage);
encStream.Write(plainBytes, 0, plainBytes.Length);
encStream.FlushFinalBlock();
byte[] encryptedBytes = new byte[ms.Length];
ms.Position = 0;
ms.Read(encryptedBytes, 0, (int)ms.Length);
encStream.Close();
return Convert.ToBase64String(encryptedBytes);
}
For Decrypting
public string DecryptMessage(string encryptedBase64)
{
TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider();
des.IV = new byte[8];
PasswordDeriveBytes pdb = new PasswordDeriveBytes(Key, new byte[0]);
des.Key = pdb.CryptDeriveKey("RC2", "MD5", 128, new byte[8]);
byte[] encryptedBytes = Convert.FromBase64String(encryptedBase64);
MemoryStream ms = new MemoryStream(encryptedBase64.Length);
CryptoStream decStream = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
decStream.Write(encryptedBytes, 0, encryptedBytes.Length);
decStream.FlushFinalBlock();
byte[] plainBytes = new byte[ms.Length];
ms.Position = 0;
ms.Read(plainBytes, 0, (int)ms.Length);
decStream.Close();
return System.Text.Encoding.UTF8.GetString(plainBytes);
}
Honestly speaking, I am not sure and clear about each line of code what does it do very specifically but shall make a update on this.








Encryptor


Decryptor

No comments:

Post a Comment