I am coding an encryption/decryption aes utility with specific requirements: -AES/CBC/PKCS7 -256-Bit Key provided as base64 string -IV provided as base64 string
So I am trying to encryp/decrypt this string "1234567890123456" using the same key and IV. Encryption runs fine but when trying to decrypt the encrypted string I get the "Padding is invalid and cannot be removed" exception. What am I missing?
//This is the calling test method
public void Test_AESEncryption_Decrypt()
{
try
{
var encoding = Encoding.ASCII;
var key = encoding.GetString(Convert.FromBase64String("JVSwvtTHhGHKmH7HIj5clsfQRXGg9ZZ0cOojoAPcGg0="));
var iv = encoding.GetString(Convert.FromBase64String("IgEfBiIIHBANIRccFhwJDg=="));
var strtoencrypt = "1234567890123456";
var encrypted = AESEncryption.Encrypt(encoding,strtoencrypt, key, iv, CipherMode.CBC, PaddingMode.PKCS7,128);
var decrypted = AESEncryption.Decrypt(encoding,encoding.GetString(encrypted), key, iv, CipherMode.CBC, PaddingMode.PKCS7,128);
Assert.AreEqual(strtoencrypt, decrypted);
}
catch (Exception ex)
{
Assert.Fail(ex.Message);
}
}
//This is my Utility Class:
public static class AESEncryption {
public static byte[] Encrypt(Encoding encoding, string strtoencrypt, string key, string iv, CipherMode mode, PaddingMode padding, int blocksize){
var mstream = new MemoryStream();
using (var aes = new AesManaged())
{
var keybytes = encoding.GetBytes(key);
aes.BlockSize = blocksize;
aes.KeySize = keybytes.Length * 8;
aes.Key = keybytes;
aes.IV = encoding.GetBytes(iv);
aes.Mode = mode;
aes.Padding = padding;
using (var cstream = new CryptoStream(mstream, aes.CreateEncryptor(aes.Key, aes.IV), CryptoStreamMode.Write))
{
var bytesToEncrypt = encoding.GetBytes(strtoencrypt);
cstream.Write(bytesToEncrypt, 0, bytesToEncrypt.Length);
cstream.FlushFinalBlock();
}
}
var encrypted = mstream.ToArray();
return encrypted;
}
public static string Decrypt(Encoding encoding,string strencrypted, string key, string iv, CipherMode mode, PaddingMode padding, int blocksize)
{
var decrypted = "";
using (var aes = new AesManaged())
{
var keybytes = encoding.GetBytes(key);
aes.BlockSize = blocksize;
aes.KeySize = keybytes.Length * 8;
aes.Key = keybytes;
aes.IV = encoding.GetBytes(iv);
aes.Mode = mode;
aes.Padding = padding;
using (var mstream = new MemoryStream(encoding.GetBytes(strencrypted)))
{
using (var cstream = new CryptoStream(mstream, aes.CreateDecryptor(aes.Key, aes.IV), CryptoStreamMode.Read))
{
using (var sreader = new StreamReader(cstream))
{
decrypted = sreader.ReadToEnd();
}
}
}
}
return decrypted;
}
}