Search code examples
encryptionaespaddingencryption-symmetric

AES padding ambiguity


I have been implementing AES in C and I am now finalising the program by implementing padding. Reading lots of other SO questions on the padding topic I have found that a popular way to do this is by filling each of the remaining places in the state with the number of places left. For example if I only had 12 bytes to encrypt, I would pad the remaining 4 bytes with 4. My question is when decrypting if I have a block which is full but ends in a 1, how do I know if this is one byte of padding or just the value 1?

DISCLAIMER: I know this program should never be used in production as it probably has all sorts of different insecurities. I am doing this for fun, not to encrypt top secret documents.


Solution

  • What you're describing is the PKCS#7 padding.

    In order to disambiguate, you always need to have padding. Additionally, the plaintext for modes like ECB or CBC mode needs to be a multiple of the block size.

    Both constraints put together lead to a simple solution: you always add padding up to the next multiple of the block size. If the plaintext is already a multiple of the block size, then you add a full block of padding where each byte represents 16 (for AES).