Jonas Schnelli
Jonas Schnelli

Reputation: 10005

pre-calculate the size of a AES256 encrypted "buffer" in c

Ho do i calculate the size of a AES256 encrypted file/buffer.

I do malloc of (n + AES_BLOCK_SIZE -1) bytes (where n is the unencrypted buffer size).

But will the size of the encrypted buffer always be that size? can it also be "smaller"?

Any idea how i pre-calculate the exact size?

Thanks

Upvotes: 2

Views: 3634

Answers (2)

Paŭlo Ebermann
Paŭlo Ebermann

Reputation: 74750

It depends on the padding you are using. The most common padding scheme (as it is reversible and contains a slight integrity check) is PKCS#5-padding: This appends a number of bytes such that the final size is a multiple of the block size, and at least one byte is appended. (Each appended byte than has the same value as the number of bytes appended.)

I.e. at most one full block (16 bytes for AES) will be appended.

n + AES_BLOCK_SIZE is always enough (and in some cases just enough), but you can calculate it more precise as n + AES_BLOCK_SIZE - (n % AES_BLOCK_SIZE).

Note that there are some modes of operation which don't need padding at all, like CTR, CFB and OFB mode. Also note that you often want to transmit the initialization vector (another full block), too.

Upvotes: 5

Heath Hunnicutt
Heath Hunnicutt

Reputation: 19457

AES is "block" encryption. It has a 128-bit block size. This means that it always takes as input a 128-bit block (16 bytes) and always outputs a same-sized block.

If your input is not a multiple of 16 bytes, you should append some data (perhaps bytes containing the value zero) to round it out.

If your data is more than 16 bytes, you will be encrypting multiple blocks, and will need to call your AES encryption function as many times as you have input blocks.

If you are only allocating space for the output, malloc(AES_BLOCK_SIZE); would be the allocation you seek. Don't add the input size or subtract one byte.

Upvotes: 1

Related Questions