TutRam - 1 year ago 82

Java Question

I would like to know the size of data after AES encryption so that I can avoid buffering my post-AES data(on disk or memory) mainly for knowing the size.

I use 128 bit AES and

`javax.crypto.Cipher`

`javax.crypto.CipherInputStream`

A few tests performed with various input sizes show that, the post encryption size calculated as below is correct:

`long size = input_Size_In_Bytes;`

long post_AES_Size = size + (16 - (size % 16));

But I am not sure whether the above formula is applicable for all possible input sizes.

Is there a way to calculate the size of data after applying AES encryption – in advance without having to buffer the encrypted data(on disk or memory) to know its post-encryption size?

Answer Source

AES has a fixed block size of 16-bytes regardless key size. Assuming you use PKCS 5/7 padding, use this formula,

```
cipherLen = (clearLen + 16) % 16;
```

Please note that if the clear-text is multiple of block size, a whole new block is needed for padding. Say you clear-text is 16 bytes. The cipher-text will take 32 bytes.

You might want to store IV (Initial Vector) with cipher-text. In that case, you need to add 16 more bytes for IV.