I am facing the AES padding issue. i am using the codes suggested in (generate a 128-bit string in C#) by Alcides Soares FIlho. Please note that my encryption side code is ...
private string Encrypt(string clearText)
{
string EncryptionKey = "I love chocolate";
byte[] clearBytes =
System.Text.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 });
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();
}
clearText = Convert.ToBase64String(ms.ToArray());
}
}
return clearText;
}
Also, the value I am passing to cleartext is " Z4YAZZSQ 001F295E2589AWAN HANS". The encryption is happening. But decryption is failing.
decryption side code
private string Decrypt(string cipherText)
{
string EncryptionKey = "I love chocolate";
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 =
System.Text.Encoding.Unicode.GetString(ms.ToArray());
}
}
return cipherText;
}
I should be able to get back " Z4YAZZSQ 001F295E2589AWAN HANS"
but the following error is coming " padding is invalid and cannot be removed " Please suggest the solution.