#Why this matters
Strong primitives such as AES-256 and SHA-256 rarely break through brute force. Instead, systems fail when implementations leak decryption metadata per request, expose hash chaining state in naive MACs, or exit early when comparing secrets.
These three flaws define modern implementation cryptanalysis: CBC padding oracles break confidentiality without the AES key, length-extension attacks forge tags on H(secret || message), and timing side channels extract secrets byte by byte.
#CBC padding oracle attacks
In 16-byte AES-CBC mode, plaintext is padded with PKCS#7 before encryption: if k padding bytes are needed (1 <= k <= 16), each appended byte holds value k (0x01, 0x02 0x02, and so on, up to a full block of sixteen 0x10 bytes). During decryption of block C_i, the cipher computes the raw intermediate block I_i = D_K(C_i) and XORs it with the previous ciphertext block C_{i-1} (or IV when i = 1):
P_i[j] = I_i[j] XOR C_{i-1}[j]
A padding oracle exists whenever a server decrypts an attacker-controlled ciphertext and reveals whether PKCS#7 unpadding succeeded - through distinct HTTP status codes (500 vs 400), error strings ("Invalid padding" vs "Invalid JSON"), or response time.
To recover P_i byte by byte from index 15 down to 0:
- Send a crafted two-block payload
C'_{i-1} || C_iand varyC'_{i-1}[15]across0..255until the oracle accepts the padding. - Verify it is
0x01(not an accidental0x02 0x02tail) by flippingC'_{i-1}[14]; if padding stays valid,P'_i[15]is truly0x01. - Compute the intermediate byte
I_i[15] = C'_{i-1}[15] XOR 0x01, then recover the real plaintext byteP_i[15] = I_i[15] XOR C_{i-1}[15]. - To solve byte
14, setC'_{i-1}[15] = I_i[15] XOR 0x02so the tail byte becomes0x02, then brute-forceC'_{i-1}[14]until the oracle signals valid0x02 0x02padding. Repeat across all 16 bytes.
Each 16-byte block requires at most 16 * 256 = 4096 oracle queries (around 2048 on average). The exact same intermediate-state recovery works in reverse (CBC-R): an attacker who can query the oracle can forge an arbitrary multi-block plaintext by solving I_i from right to left and setting C_{i-1} = I_i XOR desired_plaintext_i.
def decrypt_block(prev_block: bytes, target_block: bytes, oracle) -> bytes:
intermediate = bytearray(16)
plaintext = bytearray(16)
for pos in range(15, -1, -1):
pad_val = 16 - pos
prefix = bytearray(16)
for k in range(pos + 1, 16):
prefix[k] = intermediate[k] ^ pad_val
for guess in range(256):
prefix[pos] = guess
if oracle(bytes(prefix) + target_block):
# Guard against false 0x02 0x02 match when solving pos == 15
if pos == 15:
probe = bytearray(prefix)
probe[14] ^= 1
if not oracle(bytes(probe) + target_block):
continue
intermediate[pos] = guess ^ pad_val
plaintext[pos] = intermediate[pos] ^ prev_block[pos]
break
return bytes(plaintext)#Hash length-extension attacks
Merkle-Damgard hash functions (MD5, SHA-1, SHA-256, SHA-512) process input in fixed-size blocks (64 bytes for SHA-256; 128 bytes for SHA-512). The compression function updates an internal chaining state one block at a time, and pads the final block with 0x80, zero bytes, and a 64-bit big-endian bit length (128-bit for SHA-512).
When an application authenticates messages with tag = SHA256(secret || message), the output digest is the full 256-bit internal chaining state right after processing secret || message || md_pad. An attacker who knows message, the original tag, and len(secret) (or guesses len(secret) over a small range) does not need secret:
- Load
taginto the SHA-256 chaining registers as the initial state and set the processed byte counter to the padded block boundarylen(secret || message || md_pad). - Feed an arbitrary suffix
extension(for example,&role=admin) through SHA-256 compression. - Submit
message || md_pad || extensiontogether with the newly computed digest. The server hashessecret || message || md_pad || extensionand produces the exact same digest.
import hashpumpy
orig_msg = b"role=guest"
orig_sig = "9b2a4f..." # SHA256(secret || b"role=guest") from lab endpoint
for key_len in range(8, 33):
forged_sig, forged_msg = hashpumpy.hashpump(
orig_sig, orig_msg, b"&role=admin", key_len
)
# Submit (forged_msg, forged_sig) to the lab verifier until acceptedLength extension fails completely against HMAC (H((K XOR opad) || H((K XOR ipad) || message)), RFC 2104) because the outer hash wraps the inner state with the secret key. SHA-3 (Keccak) and KMAC are also immune because the sponge construction hides its internal capacity bits from the output.
#Side-channel timing attacks
Even when math and message formats are sound, non-constant-time execution leaks secrets through timing.
- Early-exit string or MAC comparisons: Standard equality (
==in Python ormemcmpin C) returnsFalseat the first mismatched byte. Over a local link or averaged across hundreds of samples per byte over a network to smooth out jitter, an attacker tests256values at index0until one takes slightly longer (meaning byte0matched and execution reached index1), reducing a256^32tag space to at most32 * 256 = 8192probes. - Secret-dependent branches and cache lookups: Classic square-and-multiply modular exponentiation branches on each bit of private exponent
d, while naive software AES T-table lookups index memory using secret key bytes, allowing local co-tenants to infer key bits via CPU cache timing.
| Vulnerability | Root cause | Attacker requirement | Mitigation |
|---|---|---|---|
| CBC padding oracle | Unpadded check before auth | Chosen-ciphertext queries | AEAD or Encrypt-then-MAC |
| Length extension | Raw H(secret || msg) state leak |
Known msg, tag, len(secret) |
HMAC (RFC 2104) or SHA-3/KMAC |
| Timing leak | Early-exit == or secret branch |
Repeated latency samples | hmac.compare_digest / constant-time |
#Defending and common mistakes
- Use AEAD by default: Choose AES-GCM or ChaCha20-Poly1305 (as mandated in TLS 1.3, RFC 8446). When legacy CBC is unavoidable, use Encrypt-then-MAC: verify an HMAC over
IV || Cin constant time before decrypting or checking padding. Never use MAC-then-Encrypt (which enabled Lucky13 and POODLE). - Use HMAC or KMAC: Never build
H(secret || message). Usehmac.new(..., hashlib.sha256)or SHA-3/KMAC. - Compare secrets in constant time: Use
hmac.compare_digest()in Python,crypto.timingSafeEqual()in Node.js, orsubtle.ConstantTimeCompare()in Go. - Common mistakes: Returning
400 Bad Requeston both padding and JSON errors while taking longer to parse JSON when padding succeeds (a timing padding oracle); checkinghmac.new(...).hexdigest() == tagwith==instead ofcompare_digest.
#Summary
- CBC padding oracles convert any observable PKCS#7 validation difference into block-by-block plaintext recovery (
<= 4096queries per block) and arbitrary forgery (CBC-R). - Merkle-Damgard hashes such as SHA-256 expose their internal state in the digest, enabling length extension on
H(secret || message). - Early-exit comparisons and secret-dependent branches leak secret bytes via latency differences.
- Prevent all three with AEAD (or Encrypt-then-MAC), HMAC or SHA-3/KMAC, and constant-time comparisons.