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.
The problem is in
DecryptToBytes()
.You are creating the decryptor with a different key and initialization vector than you used for encryption; you are requesting new bytes from the same key derivation function you used for deriving the key and initialization vector for encryption. Because encryption and decryption keys don't match decryption yields corrupted data and especially corrupted padding. Replace the three lines with the following one and it will work.
Note that I did not look any closer at the code and "it will work" only means that this bug will be resolved, it does not imply that other parts of the implementation are okay, too.