TL;DR
The BadPaddingException in a textbook cipher usually means your input data isn’t the right length. This guide shows you how to pad your message correctly before encrypting and unpad it after decrypting, so everything works smoothly.
Understanding the Problem
Textbook ciphers (like AES in ECB mode) work on fixed-size blocks of data. If your message isn’t a multiple of that block size, you need to add extra data – called padding – to make it fit. If the padding is incorrect or missing, decryption will fail with a BadPaddingException.
Solution: PKCS#7 Padding
PKCS#7 (also known as BSD padding) is a common and reliable way to pad data. Here’s how it works:
- Determine the Block Size: Find out the block size of your cipher. For AES, this is typically 16 bytes (128 bits).
- Calculate Padding Length: Figure out how many padding bytes you need to add. This is equal to the block size minus the length of your message (in bytes) modulo the block size. If the message length *is* a multiple of the block size, add a full block of padding.
- Add Padding Bytes: Append that number of bytes to the end of your message. Each padding byte should have a value equal to the number of padding bytes you added. For example, if you need to add 3 padding bytes, each byte will be
0x03.
Example in Python
Here’s how to implement PKCS#7 padding and unpadding in Python:
Padding
def pad(data, block_size):
padding_length = block_size - (len(data) % block_size)
padding = bytes([padding_length] * padding_length)
return data + padding
Unpadding
def unpad(data, block_size):
if len(data) % block_size != 0:
raise ValueError("Data is not a multiple of the block size")
padding_length = data[-1]
return data[:-padding_length]
Step-by-Step Instructions
- Pad Before Encryption: Always pad your message *before* you encrypt it. Use the
pad()function above (or an equivalent in your chosen language). - Unpad After Decryption: After decrypting, remove the padding using the
unpad()function. This will give you back your original message. - Check Block Size: Double-check that you’re using the correct block size for your cipher. A wrong block size will lead to incorrect padding and decryption errors.
- Error Handling: Implement error handling in your
unpad()function (like the example above) to catch cases where the data isn’t properly padded. This helps you identify problems quickly.
Common Mistakes
- Incorrect Block Size: Using the wrong block size is the most common cause of padding errors.
- Missing Padding: Forgetting to pad at all will definitely cause an error.
- Invalid Padding Value: The padding bytes must equal the number of padding bytes added.

