MichaelAttard
MichaelAttard

Reputation: 2158

Precalculating AES output length

I am building a file transfer protocol that runs over TCP. I am encrypting data before sending it. Is it possible to calculate the size of the ciphertext before actually encrypting?

I want to send the filesize to the client so he knows when the datastream has ended, while pushing the ciphertext to the stream as soon as it is output.

To encrypt I am using the RijndaelManaged .NET class.

For example, a file of size 634 bytes is encrypting to 660 bytes.

Using the formula I found, and a block size of 16:

(inputSize / blockSize + 1) * blockSize

I am getting 650 bytes. Why is there the discrepancy?

Examples of input - output size pairs (in bytes):

Input: 905296 Output: 905332

Input: 82320 Output: 82356

Input: 308 Output: 340

Upvotes: 2

Views: 351

Answers (1)

deviantfan
deviantfan

Reputation: 11434

The formula you found is not completely correct.
Given ECB or CBC (the only choices in this class):
Calculate (Bytecount / Blocksize) and omit the decimal part
Then add 1 for padding, then multiply with Blocksize.

634/16 = 39.625 => 40
40 * 16 = 640

The 10 other bytes...probably a header or something like that.
MS is known to add own stuff everywhere.

Upvotes: 1

Related Questions