Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the length of a CryptoStream in .Net

I'm working on software which encrypts/decrypts files. I would like to be able to guess the length of the data after the encryption but I can't use CryptoStream.Length (It throws a NotSupportedException). Is there any way to guess it ?

I'm using RijndaelManaged (.Net Framework 4.0)

like image 761
Bahaïka Avatar asked Oct 26 '11 18:10

Bahaïka


Video Answer


1 Answers

This says it much better than I can http://www.obviex.com/Articles/CiphertextSize.aspx

From there:

In the most generic case, the size of the ciphertext can be calculated as:

CipherText = PlainText + Block - (PlainText MOD Block)

where CipherText, PlainText, and Block indicate the sizes of the ciphertext, plaintext, and encryption block respectively. Basically, the resulting ciphertext size is computed as the size of the plaintext extended to the next block. If padding is used and the size of the plaintext is an exact multiple of the block size, one extra block containing padding information will be added.

Let's say that you want to encrypt a nine-digit Social Security Number (SSN) using the Rijndael encryption algorithm with the 128-bit (16-byte) block size and PKCS #7 padding. (For the purpose of the illustration, assume that dashes are removed from the SSN value before the encryption, so that "123-45-6789" becomes "123456789", and the value is treated as a string, not as a number.) If the digits in the SSN are defined as ASCII characters, the size of the ciphertext can be calculated as:

CipherText = 9 + 16 - (9 MOD 16) = 9 + 16 - 9 = 16 (bytes)

Notice that if the size of the plaintext value is the exact multiple of the block size, an extra block containing padding information will be appended to the ciphertext. For example, if you are to encrypt a 16-digit credit card number (defined as a 16-character ASCII string), the size of the ciphertext will be:

CipherText = 16 + 16 - (16 MOD 16) = 16 + 16 - 0 = 32 (bytes)

like image 176
Adam Tuliper Avatar answered Oct 17 '22 08:10

Adam Tuliper