Introduction
This tip presents an example of encrypt and decrypt password. In real scenarios, the user passwords are stored in database as in encrypted formatted for more security. This is a very good practice to store encrypted passwords in database.
Using the Code
In ASP.NET codebehind, first import the required namespace:
System.Security.Cryptography;
In encrypted method, code is below:
private string Encrypt(string Text)
{
string EncryptionKey = "AMAR2SPBNRAP390";
byte[] clearBytes = Encoding.Unicode.GetBytes(Text);
using (Aes encryptor = Aes.Create())
{
Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[]
{ 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
encryptor.Key = pdb.GetBytes(32);
encryptor.IV = pdb.GetBytes(16);
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(),
CryptoStreamMode.Write))
{
cs.Write(clearBytes, 0, clearBytes.Length);
cs.Close();
}
Text = Convert.ToBase64String(ms.ToArray());
}
}
return Text;
}
In decrypted method, code is below:
private string Decrypt(string cipherText)
{
string EncryptionKey = "AMAR2SPBNRAP390";
byte[] cipherBytes = Convert.FromBase64String(cipherText);
using (Aes encryptor = Aes.Create())
{
Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[]
{ 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
encryptor.Key = pdb.GetBytes(32);
encryptor.IV = pdb.GetBytes(16);
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(),
CryptoStreamMode.Write))
{
cs.Write(cipherBytes, 0, cipherBytes.Length);
cs.Close();
}
cipherText = Encoding.Unicode.GetString(ms.ToArray());
}
}
return cipherText;
}
Hope these two methods will be helpful to all.
Wherever you required to encrypt and decrypt string, just call these methods with parameter of the encrypted string just enough. This is very useful to all.
Points of Interest
This is most useful and will be required for all whenever users have secure passwords.
History