PKCS#7 Padding

PKCS#7 Padding (also known as PKCS#5 padding for 8-byte blocks) is a scheme for padding plaintext to a multiple of the block size before encryption. Each padding byte contains the value of the total padding length.

How It Works

// Block size: 16 bytes (AES)
// Plaintext: "Hello" (5 bytes)
// Need: 11 bytes of padding

// Padded: "Hello" + [0x0B 0x0B 0x0B 0x0B 0x0B 0x0B 0x0B 0x0B 0x0B 0x0B 0x0B]
//         5 bytes  +  11 bytes of value 0x0B (11 in decimal)

// If plaintext is exact multiple of block size:
// Add full block of padding (16 x 0x10)

Padding Examples

Block size: 16 bytes

Length 14: [data...] [0x02 0x02]
Length 15: [data...] [0x01]
Length 16: [data...] [full block: 0x10 × 16]
Length 1:  [data] [0x0F × 15]

Unpadding (Validation)

1. Read last byte (n)
2. Verify: 1 ≤ n ≤ block_size
3. Check last n bytes all equal n
4. Remove last n bytes

// Invalid padding examples:
[...0x00]        // 0 is invalid
[...0x11]        // > 16 is invalid for 16-byte blocks
[...0x03 0x03 0x02]  // Not all padding bytes match

Security Implications

  • Padding validation errors enable Padding Oracle Attacks
  • Must validate in constant time
  • Error messages must not distinguish padding errors

Better Alternatives

  • Use authenticated encryption (GCM) - no padding needed
  • Use CTR mode - stream cipher, no padding
  • Always use Encrypt-then-MAC

See Also