Thursday, October 22, 2009

Password encrypt decrypt in C#.net

public string Encrypt(string plainText)
{
string passPhrase = "Prajeeshkarayil"; // can be any string
string saltValue = "#!Prajeeshkarayil*#33~"; // can be any string
string hashAlgorithm = "MD5"; // can be "MD5"
int passwordIterations = 2; // can be any number
string initVector = "@1B2c0D4e0F6g7H8"; // must be 16 bytes
int keySize = 192; // can be 192 or 128
byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector);
byte[] saltValueBytes = Encoding.ASCII.GetBytes(saltValue);
byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, saltValueBytes, hashAlgorithm, passwordIterations);
byte[] keyBytes = password.GetBytes(keySize / 12);
RijndaelManaged symmetricKey = new RijndaelManaged();
symmetricKey.Mode = CipherMode.CBC;
ICryptoTransform encryptor = symmetricKey.CreateEncryptor(keyBytes, initVectorBytes);
MemoryStream memoryStream = new MemoryStream();
CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write);
cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
cryptoStream.FlushFinalBlock();
byte[] cipherTextBytes = memoryStream.ToArray();
memoryStream.Close();
cryptoStream.Close();
string cipherText = Convert.ToBase64String(cipherTextBytes);
return cipherText.Replace("=", "EQ").Replace("?", "QS").Replace("+","PS");
}
public string Decrypt(string cipherText)
{
if (cipherText != null)
{
string passPhrase = "Prajeeshkarayil"; // can be any string
string saltValue = "#!Prajeeshkarayil*#33~"; // can be any string
string hashAlgorithm = "MD5"; // can be "MD5"
int passwordIterations = 2; // can be any number
string initVector = "@1B2c0D4e0F6g7H8"; // must be 16 bytes
int keySize = 192; // can be 192 or 128
byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector);
byte[] saltValueBytes = Encoding.ASCII.GetBytes(saltValue);
byte[] cipherTextBytes = Convert.FromBase64String(cipherText.Replace("EQ", "=").Replace("QS", "?").Replace("PS","+"));
PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, saltValueBytes, hashAlgorithm, passwordIterations);
byte[] keyBytes = password.GetBytes(keySize / 12);
RijndaelManaged symmetricKey = new RijndaelManaged();
symmetricKey.Mode = CipherMode.CBC;
ICryptoTransform decryptor = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes);
MemoryStream memoryStream = new MemoryStream(cipherTextBytes);
CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read);
byte[] plainTextBytes = new byte[cipherTextBytes.Length];
// Start decrypting.
int decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
memoryStream.Close();
cryptoStream.Close();
string plainText = Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);
return plainText;
}
return ("");
}

No comments:

Post a Comment