Take the 2-minute tour ×
Information Security Stack Exchange is a question and answer site for Information security professionals. It's 100% free, no registration required.

I'm a bit confused with AES-256, CBC, and how it works with padding (PKCS#7).

Whenever I encrypt data of multiples of 16 bytes (the block size), extra 16 bytes are always padded at the end.

For instance, a 1600 byte file turns into a 1616 byte encrypted file.

If I look into the file with a hex editor, the last 16 bytes are not all zeros at all. I don't see any particular pattern either.

An explanation would be appreciated!

share|improve this question

1 Answer 1

up vote 2 down vote accepted

The padding is done before encryption. It ensures that what will be given to the encryption algorithm can be split into an integral number of blocks (16 bytes per block with AES). AES encrypts the whole, data and padding, and encrypted data "looks random".

After decryption, the original contents of the padding are revealed, and will exhibit the proper structure (namely that the extra bytes all have value n if n extra bytes were added -- n = 16 in your example).

share|improve this answer
    
I still don't get how padding can be done before encryption, because often we are encrypting the whole data in small pieces at a time, until we hit the end. At the end there is usually a "finalize" function that is supposed to take care of the padding. So how did it happen before encryption? Can you please elaborate? –  user21203 Feb 27 '13 at 21:19
2  
Application sends data. When a full block is received, the block is encrypted. At any one time, between 0 and 15 bytes are still buffered. The "finalize" function is called: between 1 and 16 bytes are appended to the buffered data (to reach the length of 16), and that final block is encrypted like all the others. If 0 bytes were buffered at that point, 16 padding bytes are appended (all of numerical value 16), and that extra block is encrypted (leading to the seemingly random bytes). –  Tom Leek Feb 27 '13 at 21:27

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.