Padding is a defined way to make variable-length data fit a fixed-size cryptographic input. Block ciphers require complete blocks, so padding fills a short final block before encryption and must be recognized correctly after decryption. Fixed-size RSA inputs and Merkle–Damgård hash processing also use padding rules. section 5.2 section 10.3
The scheme determines whether padding can be distinguished from data. Zero padding is ambiguous when plaintext itself ends in zero bytes. ANSI X.923 uses zero bytes followed by a byte recording their count. PKCS#7 writes the total padding length into every added byte; when input already fits exactly, it adds a whole block whose bytes equal the block size. section 5.2
Figure 5.3 Example: X denotes padding bytes in the last block for a cipher with a block size of 8 bytes.
Use the block diagram to see why a partial final plaintext block needs added bytes before a cipher that accepts only 8-byte blocks can process it. section 5.2
PKCS#7 in an 8-byte block
If a final plaintext fragment is 4 bytes long, PKCS#7 appends four bytes: 0x04 0x04 0x04 0x04. The repeated value says that four bytes were added. ANSI X.923 would instead use 0x00 0x00 0x00 0x03 for the same illustrated case. section 5.2
Padding is security-sensitive parsing, not merely formatting. A padding oracle reveals whether modified ciphertext decrypts to valid padding; even that one-bit result can enable recovery of the original plaintext. Error details and response timing can both leak padding validity. section 5.4 section 10.3
Handle padding defensively:
- Return a general decryption failure rather than an invalid-padding error, and avoid observable timing differences that reveal validation results. section 10.3
- Enforce every required byte and field of structured padding; incomplete PKCS#1 v1.5 validation can enable signature forgery. section 9.6.1 section 9.7
- For signature values, generate the correctly padded reference value and compare it with the input rather than loosely parsing fields around a separator. section 10.3
- Use probabilistic RSA padding where required so identical plaintexts do not produce identical ciphertexts. section 8.5
SHA-256 padding in a length-extension attack
A demonstrated SHA-256 padding generator appends one 1 bit, adds zero bits until the message length is 448 modulo 512, then appends the original bit length as a 64-bit big-endian integer. Knowing this padding lets an attacker extend a vulnerable secret-prefix MAC calculation from its exposed digest state. section 7.3.2


















