</body></html>��������
// Processed: 636 Buffer size: 640
So the additional bytes size is not consistent, I cannot just decrement 'by some'.
What am I doing wrong when calculating the size of the output array?
–
It's relevant to padding.
AES encrypts block by block, and every block must be 128 bits long. Passing in some data that is not divisible into blocks of 128 bits means that the final block of plaintext must be padded until it is 128 bits in size.
getOutputSize
is returning you the the size of the ciphertext should you encrypt. Remember that the plaintext is padded and then encrypted, so the input size to output size is the same. You can see this because 636 mod 16 = 12
and 636 - 12 + 16 = 640
. E.g. it is rounding up to the nearest multiple of 16 because this is how many extra padding bytes were included before encryption.
Since you are using this while decrypting, the array is larger than required because you are allocating the bytes that would be required. getOutputSize
can be used for both encryption and decryption provided you are aware that it is a "worst-case" scenario for buffer allocation.
–
–
–
TL;DR: getOutputSize() lets you know what sized buffer to allocate (a worst case), return values from processBytes/doFinal tell you how much of the buffer was actually used (exact).
You are using PaddedBufferedBlockCipher for decryption (above code defaults to PKCS7 padding). getOutputSize() cannot determine the exact amount of output plaintext until it actually sees the decrypted data for the final block, so the returned value will be an upper bound, which is why the return value is there for processBytes/doFinal to let you know how much was actually output.
For simplicity, PaddedBufferedBlockCipher also ignores the details of the particular padding scheme used - it assumes only that the final block could contain some amount of padding that will be removed.
The unused bytes at the end of 'outBuf' are not written to by the cipher. In particular, they will not contain the padding. Presumably the "weird characters" are zero bytes from the array initialisation.
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.