I'm sorry about the confusing title, I honestly had no clue what to call it! I was tossing up whether this belong on one of the security/crypto exchange sites but as this is predominantly a programming question I will post it here. Feel free to move it!
I have an AES crypto stream, and as AES pads the original data with blocks, the resulting encrypted data is almost always a different size to the original unencrypted data. When decrypting, you need to know how many bytes to read from the crypto stream (how many unencrypted bytes there are). I was originally planning on sending the original, unencrypted data length in the packet but then I thought of another way. If I just read 4096 bytes from the Crypto Stream and store how many actual bytes were read, I can then copy the correct amount of bytes to a new array and use that.
Is it safe to do that? My code is the following:
using (ICryptoTransform crypt = AES.CreateDecryptor())
{
using (MemoryStream memStrm = new MemoryStream(data))
{
using (CryptoStream cryptStrm = new CryptoStream(memStrm, crypt, CryptoStreamMode.Read))
{
byte[] bytes = new byte[size];
int read = cryptStrm.Read(bytes, 0, 4096);
byte[] temp = new byte[read];
Array.Copy(bytes, temp, read);
return temp;
}
}
}
By safe I mean, will it always produce correct decrypted data?