Post

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.

  1. What It’s For
  2. Examples
  3. Edge Case

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)

58b3a9

After Padding (8 Bytes)

58b3a90505050505


Example 2

Before Padding (14 Bytes)

c3074bb2b49f5ba9
a60b51306d2c

After Padding (16 Bytes)

c3074bb2b49f5ba9
a60b51306d2c0202


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)

58b3a932078cfd19

After Padding (16 Bytes)

58b3a932078cfd19
0808080808080808
This post is licensed under CC BY 4.0 by the author.