Sunday, November 01, 2009

Encrypting-Decrypting the password in C#

Encrypting the password in .NET become ease,DESCryptoServiceProvider enables the developer to encrypt the plain text in to encrypted form.

Code snippet as below :


public static byte[] Encrypt(string txtPassword, SymmetricAlgorithm key)
{
MemoryStream mStream = new MemoryStream();
CryptoStream cStream = new CryptoStream(mStream, key.CreateEncryptor(), CryptoStreamMode.Write);
StreamWriter sw = new StreamWriter(cStream);
sw.WriteLine(txtPassword);
sw.Close();
cStream.Close();
byte[] buffer = mStream.ToArray();
mStream.Close();
return buffer;
}


Decrypting the encrypted bytes:

public static string Decrypt(byte[] CryptedBytes, SymmetricAlgorithm key)
{
MemoryStream mStream = new MemoryStream(CryptedBytes);
CryptoStream cStream = new CryptoStream(mStream, key.CreateDecryptor(), CryptoStreamMode.Read);
StreamReader sr = new StreamReader(cStream);
string PlainTxt = sr.ReadLine();
sr.Close();
cStream.Close();
mStream.Close();
return PlainTxt;
}

In Database,I used to save these bytes in Password column.While retrieving/Checking the Password,I used the Decrypt the function.So Password column will have encrypted text that easily human can't read or memorize.

For using this code you need to import System.Security.Cryptography class into your application.