Course contentsShow
← Security
Lesson 108 of 3,0523. Symmetric Cryptography Deep DiveFree lesson

PKCS#7 and PKCS#5 Padding Schemes

Understand the most common padding standards, how they work, and the subtle differences between PKCS#5 and PKCS#7.

PKCS#7 and PKCS#5 Padding Schemes

What you'll learn: How the two most common padding standards fill incomplete cipher blocks and why they're actually almost the same thing.

The Core Idea

When block ciphers like AES process data, they need complete blocks (8 or 16 bytes). But real-world messages rarely end exactly on a block boundary. PKCS#5 and PKCS#7 solve this by adding padding bytes in a clever, unambiguous way: each padding byte contains the number of padding bytes added.

Think of it like packing boxes: if you have 13 apples and need to fill a 16-apple box, you add 3 foam pieces. But instead of plain foam, you write "3" on each piece so the receiver knows exactly how many to remove.

How It Works

If your block size is 16 bytes and your message is 13 bytes short, you add 3 bytes, each containing the value 0x03:

[data data data ... data | 03 03 03]

If the message perfectly fills the block? You add a full block of padding (all bytes set to the block size value) to avoid ambiguity. This guarantees you can always safely remove padding.

PKCS#5 vs PKCS#7: The Difference

Here's the subtle distinction:

  • PKCS#5 was defined specifically for 8-byte blocks (originally for DES)
  • PKCS#7 generalizes the same scheme for any block size (1-255 bytes)

In practice, when people say "PKCS#5 padding," they usually mean PKCS#7 applied to 8-byte blocks. The algorithm is identical; only the scope differs.

Why This Matters

This padding scheme is deterministic and removable without needing separate metadata. The receiver simply looks at the last byte, verifies all padding bytes match, and strips them off.

Key Takeaway: PKCS#7 padding fills incomplete blocks by adding N bytes each containing the value N; PKCS#5 is the same scheme limited to 8-byte blocks, though the terms are often used interchangeably.