I want to encrypt and decrypt a string using AES Algorithm in asp.net with c#. I want to encrypt a string with a key that can be randomly generated and decrypt and get the string encrypted in AES Algorithm. I tried encryption and decryption in AES but decrypted value is not matching with the string I have encrypted.Also I need to generate the encryption key randomly. Currently I have done with a key obtained statically.
What I have tried:
The code done is as below:
Encryption Method
public static string AES_Encrypt(string clearText, ref string keyStr)
{
string EncryptionKey = "MAKV2SPBNI99212";
byte[] clearBytes = Encoding.Unicode.GetBytes(clearText);
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 });
byte[] key=new byte[16];
key= pdb.GetBytes(16);
encryptor.Key =key;
encryptor.IV = key;
keyStr = System.Text.Encoding.UTF8.GetString(key);
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
{
cs.Write(clearBytes, 0, clearBytes.Length);
cs.Close();
}
clearText = Convert.ToBase64String(ms.ToArray());
}
}
return clearText;
}
Decryption Method
public static string AES_Decrypt(string cipherText, Aes encryptor)
{
byte[] cipherBytes = Convert.FromBase64String(cipherText);
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;
}