I implement the following method:
public static byte[] AESDecrypt(byte[] data, ICryptoTransform transform)
{
using (MemoryStream stream = new MemoryStream(data))
using (CryptoStream cstream = new CryptoStream(stream, transform, CryptoStreamMode.Read))
using (MemoryStream output = new MemoryStream())
{
byte[] buffer = new byte[4000];
int r;
while ((r = cstream.Read(buffer, 0, buffer.Length)) > 0)
{
output.Write(buffer, 0, r);
}
stream.Close();
return output.ToArray();
}
}
I am using this method to decrypt a sequence of 16 bytes blocks, the transform
parameter is initialized once at the beginning:
AesCryptoServiceProvider provider = new AesCryptoServiceProvider();
provider.Mode = CipherMode.ECB;
provider.KeySize = 128;
provider.BlockSize = 128;
provider.Key = key;
provider.Padding = PaddingMode.PKCS7;
transform = provider.CreateDecryptor();
My problem is that suddenly the method starts to produce strange output, 16 bytes block is decrypted to 27 bytes !!!!, sometimes 16 bytes are decrypted wrongly to 16 bytes, however when I restart the application the same data produce correct result, does the transform hold any state that makes this happen? what wrong thing I did that makes 16 bytes block decrypted to 27 bytes.
Any help is appreciated
`Edit:
Can someone confirm it is the same bug: Reuse ICryptoTransform objects
Edit 2:
Something to add to the correct answer:
It seems ICryptoTransform is not thread safe, so calling the above method from two threads simultaneously may cause trouble, I solved it by creating ICrypteTransform object for each thread that is using the method