views:

119

answers:

2

Hi all,

I have an application which stores some information in an encrypted state, both on file and in a database. How can I calculate what the length of the resultant cipher text will be based on the plain text input?

The encryption operation consists of using the .NET RijndaelManaged class/algorithm and then a conversion to a Base64 string prior to storage.

What I want to be able to do is to know beforehand how long the encrypted string will be for a given input so that I can limit the length of the input accordingly in relation to the storage space available for its encrypted form (if that makes sense!).

Thanks

+6  A: 

Rijndael's output is the same size as the input, rounded up to the next closest multiple of the block size (usually 128 bits, aka 16 bytes). Base64 expands its input to its output by 4/3 -- it takes 4 bytes of output to represent each 3 bytes of input.

So if you have for example an input of 70 bytes, the encrypting step will produce 80 bytes of output (closest multiple of 16 that's > 70), Base64 will turn that into 108 (81/3 times 4).

Alex Martelli
Excellent, thanks!
Lee D
If you are using PKCS7Padding (which you probably are), the encryption step will expand the length the closest _strictly_larger_ multiple. E.g. 64 bytes will become 80 bytes. You probably know that, but in your example, you write "(closest multiple of 16 that's >= 70)" rather than "(closest multiple of 16 that's > 70)".
Rasmus Faber
@Rasmus, excellent point, thanks -- my >= was one of those nasty "off by one" errors:-(. Editing answer now... thanks again!
Alex Martelli
+1  A: 

The encrypted text will be the first cipher block size multiple bigger than you text. You check your Algorithm BlockSize property. Pure Base64 encoding increases the output by a third, but this can vary if you also need to URL escape (percent encode) certain Base64 symbols (like '+' and '/').

Remus Rusanu