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

2 comments:

pavan kumar said...

hi i want to drag and drop my columns in gridview for example i am having four columns 1,2,3,4 if i drag column4 and drop it on column2 my output should be
columns:1,4,2,3
please give me a solution its urgent

Programming and Database Concepts said...

Hi Pavan,

Sorry i may be very late to reply on this.
I am bit busy and could not attend blog comments for a long time.


Regarding the expected functionality i would suggest to develop a customised html table and then provide javascript functions to update the HTML dynmically