Password Encryption and Decryption

protected void encrypt_Click(object sender, EventArgs e)
{
string enc = Encrypt(TextBox2.Text);
TextBox2.Text = enc;
}

public string Encrypt(string TextToBeEncrypted)
{
RijndaelManaged RijndaelCipher = new RijndaelManaged();
String Password = "CSC";
Byte[] PlainText = System.Text.Encoding.Unicode.GetBytes(TextToBeEncrypted);
Byte[] Salt = System.Text.Encoding.ASCII.GetBytes(Password.Length.ToString());
PasswordDeriveBytes SecretKey = new PasswordDeriveBytes(Password, Salt);
ICryptoTransform Encryptor = RijndaelCipher.CreateEncryptor(SecretKey.GetBytes(32), SecretKey.GetBytes(16));
MemoryStream memoryStream = new MemoryStream();
CryptoStream cryptoStream = new CryptoStream(memoryStream, Encryptor, CryptoStreamMode.Write);
cryptoStream.Write(PlainText, 0, PlainText.Length);
cryptoStream.FlushFinalBlock();
Byte[] CipherBytes = memoryStream.ToArray();
memoryStream.Close();
cryptoStream.Close();
string EncryptedData = Convert.ToBase64String(CipherBytes);
return EncryptedData;
}


public string Decrypt(string TextToBeDecrypted)
{
RijndaelManaged RijndaelCipher = new RijndaelManaged();
String Password = "CSC";
String DecryptedData;
try
{
Byte[] EncryptedData = Convert.FromBase64String(TextToBeDecrypted);
Byte[] Salt = System.Text.Encoding.ASCII.GetBytes(Password.Length.ToString());
PasswordDeriveBytes SecretKey = new PasswordDeriveBytes(Password, Salt);
ICryptoTransform Decryptor = RijndaelCipher.CreateDecryptor(SecretKey.GetBytes(32), SecretKey.GetBytes(16));
MemoryStream memoryStream = new MemoryStream(EncryptedData);
CryptoStream cryptoStream = new CryptoStream(memoryStream, Decryptor, CryptoStreamMode.Read);
Byte[] PlainText = new Byte[EncryptedData.Length - 1];
int DecryptedCount = cryptoStream.Read(PlainText, 0, PlainText.Length);
memoryStream.Close();
cryptoStream.Close();
DecryptedData = System.Text.Encoding.Unicode.GetString(PlainText, 0, DecryptedCount);
}
catch
{
DecryptedData = TextToBeDecrypted;
}
return DecryptedData;

}

protected void dencrypt_Click(object sender, EventArgs e)
{
string den=Decrypt(TextBox1.Text);
TextBox1.Text = den;
}

Comments

Popular posts from this blog

How to change value on selection of dropdown list control in datagid

Dictionary used for key value pair

Insert value from one table into exsiting table in oracle i.e merge