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.
// 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)
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]
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