I have been struggling with this problem for several days now. I have read all the posts out there about this padding issue - which can often be caused by an incorrect key (possibly the case here - but I'm not seeing it.
Code Below:
internal class AESEncryptionManager { private byte[] keyBytes { get; set; } private byte[] ivBytes { get; set; } private static readonly byte[] SALT = new byte[] {0x26, 0xdc, 0xff, 0x12, 0xad, 0xed, 0x7a, 0xee, 0xc5, 0xfe, 0x02, 0xaf, 0x4d, 0x08, 0x22, 0x3c}; private Rfc2898DeriveBytes keyDerivationFunction { get; set; } private AesManaged aesManaged; public AESEncryptionManager(string key) { aesManaged = new AesManaged(); aesManaged.Padding = PaddingMode.PKCS7; keyDerivationFunction = new Rfc2898DeriveBytes(key, SALT); aesManaged.KeySize = 256; aesManaged.BlockSize = 128; byte[] newKey = keyDerivationFunction.GetBytes(aesManaged.KeySize >> 3); byte[] newIv = keyDerivationFunction.GetBytes(aesManaged.BlockSize >> 3); keyBytes = newKey; ivBytes = newIv; aesManaged.Key = keyBytes; aesManaged.IV = ivBytes; } public byte[] EncryptToBytes(byte[] message) { ICryptoTransform encryptor = aesManaged.CreateEncryptor(keyBytes, ivBytes); using (MemoryStream msEncrypt = new MemoryStream()) { using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)) { csEncrypt.Write(message, 0, message.Length); csEncrypt.Close(); return msEncrypt.ToArray(); } } } public byte[] DecryptToBytes(byte[] message) { byte[] newKey = keyDerivationFunction.GetBytes(aesManaged.KeySize >> 3); byte[] newIv = keyDerivationFunction.GetBytes(aesManaged.BlockSize >> 3); ICryptoTransform decryptor = aesManaged.CreateDecryptor(newKey, newIv); using (MemoryStream msDecrypt = new MemoryStream()) { using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Write)) { csDecrypt.Write(message, 0, message.Length); csDecrypt.Close(); return msDecrypt.ToArray(); } } }
I have tried the usual things like flushing the stream, etc. Any help not already provided on MSDN or Stack Overflow would be helpful.