Cryptography - PKCS#7 Padding
This post will show how PKCS#7 Padding works for block ciphers like DES and AES. This post includes visual examples and the edge case to be aware of. PKCS#7, which includes message padding, is defined in RFC 5652.
What It’s For
Padding is used in certain block cipher modes (like ECB and CBC) when the plain-text needs to be a multiple of the block size. If we are using a 16 byte block cipher, but our plain-text is only 9 bytes, then we need to pad out our data with 7 additional bytes.
To do this we append 7 bytes all with the value of 0x07
. The general case is if we need to add N bytes to make a full block, we append N bytes each with a value of N. This works only if the block size is less than 256 bytes, since a byte can only be a value between 0 and 255. See examples below for 8 byte blocks:
Examples
Example 1
Before Padding (3 Bytes)
58 | b3 | a9 |
After Padding (8 Bytes)
58 | b3 | a9 | 05 | 05 | 05 | 05 | 05 |
Example 2
Before Padding (14 Bytes)
c3 | 07 | 4b | b2 | b4 | 9f | 5b | a9 |
a6 | 0b | 51 | 30 | 6d | 2c |
After Padding (16 Bytes)
c3 | 07 | 4b | b2 | b4 | 9f | 5b | a9 |
a6 | 0b | 51 | 30 | 6d | 2c | 02 | 02 |
Edge Case
The edge case to be aware of is when the plain-text length is a multiple of the block size. I.e. if the block size is 8, and the plain-text is of size 8, 16, 24, etc. In this case, padding still needs to be added to avoid confusion.
If no padding was added, and the plain-text ends with 02 02
or 01
, that data would be striped away as it would look like padding.
If the plain-text is a multiple of the block size B, then another block is added that contains the value B in all positions. Example below with a block size of 8:
Before Padding (8 Bytes)
58 | b3 | a9 | 32 | 07 | 8c | fd | 19 |
After Padding (16 Bytes)
58 | b3 | a9 | 32 | 07 | 8c | fd | 19 |
08 | 08 | 08 | 08 | 08 | 08 | 08 | 08 |