#Why this matters
Modern primitives such as AES-256 and SHA-256 rarely fail because someone broke their core mathematics. In production incidents and CTF challenges alike, systems fail because developers combine strong primitives in fragile ways: choosing ECB mode, decrypting unauthenticated CBC tokens, reusing stream-cipher nonces, rolling custom SHA256(secret + data) tags, or comparing secrets with non-constant-time equality checks.
To evaluate real systems systematically, cryptographers classify attacker capabilities into four standard models, ordered from weakest to strongest:
- Ciphertext-Only (COA)Attacker sees only ciphertexts; relies on frequency analysis or weak keys
- Known-Plaintext (KPA)Attacker holds fixed (plaintext, ciphertext) pairs such as known headers
- Chosen-Plaintext (CPA)Attacker queries an encryption oracle on arbitrary chosen plaintexts
- Chosen-Ciphertext (CCA)Attacker queries a decryption oracle on modified ciphertexts
Every implementation flaw below succeeds because an application unintentionally grants an attacker CPA, CCA or side-channel oracle access.
#Block cipher mode failures: ECB and CBC
Electronic Codebook (ECB) mode encrypts each 16-byte plaintext block independently with the same key. Identical plaintext blocks always map to identical ciphertext blocks -- famously demonstrated by the "ECB penguin", where an encrypted bitmap preserves the visible silhouette of the image. In web applications, ECB allows block-shuffling (reordering or swapping encrypted cookie blocks such as role fields) and a chosen-plaintext byte-at-a-time oracle: if a service returns AES-ECB(user_input + secret), an attacker who controls user_input can align block boundaries so only one unknown byte of secret sits at the end of a block, then probe at most 256 candidates per byte to recover the entire secret regardless of its length.
Cipher Block Chaining (CBC) fixes repeating patterns by XORing each plaintext block with the previous ciphertext block (C[i-1]), but without authentication it introduces two CCA vulnerabilities:
- CBC bit-flipping: during decryption,
P[i] = I[i] XOR C[i-1], whereI[i] = AES_dec(K, C[i])is the intermediate block. Flipping a bit inC[i-1]flips the exact same bit inP[i](while scramblingP[i-1]), letting an attacker alter structured fields likerole=userif no MAC covers the ciphertext. - CBC padding oracle: if a server decrypts an AES-CBC token and returns different errors -- for example
'padding error'when PKCS#7 unpadding fails versus'invalid token'when padding is valid but the payload is malformed -- it leaks a one-bit oracle. When the server confirms valid padding of valuepad_valfor a modified previous byteguess, the equationI[i][j] XOR guess == pad_valholds, revealing the intermediate byteI[i][j] = guess XOR pad_valand then the original plaintext byteP[i][j] = I[i][j] XOR C_prev[j]. Testing up to 256 byte values across each of the 16 positions decrypts an entire 16-byte block in at most16 * 256 = 4096queries without knowing the AES key.
TLS 1.3 eliminated CBC padding oracles (such as POODLE) by removing CBC modes altogether in favor of AEAD ciphers.
#Stream-cipher nonce reuse and weak RSA parameters
Stream ciphers and counter modes (AES-CTR, ChaCha20) generate a pseudorandom keystream KS from (key, nonce) and compute C = P XOR KS. If the same (key, nonce) pair is ever reused for two messages P1 and P2, XORing the two ciphertexts cancels the keystream completely:
C1 XOR C2 = (P1 XOR KS) XOR (P2 XOR KS) = P1 XOR P2
With known headers or English ASCII structure, P1 XOR P2 often reveals both plaintexts immediately. In AES-GCM, nonce reuse is even worse because it also leaks the GHASH authentication key, enabling arbitrary message forgery.
In asymmetric cryptography, textbook RSA without randomized padding (OAEP for encryption, PSS for signatures) breaks under several parameter mistakes frequently audited in reviews and CTFs:
- Small public exponent without padding: if
e = 3and a short message satisfiesm^3 < n, modular reduction never occurs, so taking the ordinary integer cube root ofcrecoversminstantly. - Common modulus reuse: encrypting the same message
munder the same modulusnwith two coprime exponentse1ande2lets an observer combine the ciphertexts using the Extended Euclidean Algorithm (a*e1 + b*e2 = 1) to recovermwithout factoringn. - Wiener's attack bound: choosing a tiny private exponent
d < (1/3) * n^(1/4)to speed up decryption allowsdto be recovered efficiently via continued fractions ofe / n.
Using standard e = 65537, properly generated keys of at least 2048 bits, and RSA-OAEP/RSA-PSS prevents all three failures.
#Hash collisions, length extension and timing side-channels
By the birthday bound, an n-bit hash function yields a collision with roughly 50% probability after about 2^(n/2) attempts rather than 2^n. Thus 128-bit MD5 has only ~2^64 generic collision strength (and much less via differential cryptanalysis), 160-bit SHA-1 fell practically in Google's SHAttered collision, and truncating even SHA-256 down to 24 bits reduces collision resistance to roughly 2^(24/2) = 2^12 (about 4096 attempts).
Classic Merkle-Damgard hashes (MD5, SHA-1, SHA-256) also suffer from hash length extension when misused as a naive MAC: SHA256(SECRET || data). Because the output digest directly exposes the internal chaining state after processing SECRET || data || padding, an attacker who knows data and guesses the byte length of SECRET can initialize SHA-256 from that digest and append extra data (such as &role=admin) to forge a valid digest for SECRET || data || padding || extra without ever knowing SECRET. Replacing it with HMAC (H(K XOR opad || H(K XOR ipad || M))) stops length extension completely because the outer keyed hash hides the inner chaining state.
Finally, timing side-channels undermine even strong MACs if verification uses standard string equality (==). Standard equality stops on the first mismatched byte, taking slightly longer when more leading bytes match. Always verify MACs and tokens in constant time with hmac.compare_digest.
import hashlib
import hmac
# 1. Toy 24-bit truncated hash birthday bound (~2^12 = 4096 attempts expected)
seen = {}
for i in range(100000):
msg = f"lab-msg-{i}".encode()
tag24 = hashlib.sha256(msg).digest()[:3]
if tag24 in seen:
print(f"24-bit collision after {i} attempts: {seen[tag24]} vs {msg}")
break
seen[tag24] = msg
# 2. Stream-cipher nonce reuse cancels the keystream under XOR
keystream = hashlib.sha256(b"demo-key:reused-nonce").digest()
p1 = b"USER=alice;ROLE=guest;"
p2 = b"USER=alice;ROLE=admin;"
c1 = bytes(a ^ b for a, b in zip(p1, keystream))
c2 = bytes(a ^ b for a, b in zip(p2, keystream))
xor_diff = bytes(a ^ b for a, b in zip(c1, c2))
assert xor_diff == bytes(a ^ b for a, b in zip(p1, p2))
print("Nonce-reuse XOR matches P1 ^ P2:", xor_diff.hex())
# 3. Safe authentication: HMAC-SHA256 + constant-time verification
secret = b"lab-hmac-secret-key"
payload = b"user=alice&role=user"
valid_tag = hmac.new(secret, payload, hashlib.sha256).hexdigest()
print("Constant-time HMAC valid:", hmac.compare_digest(valid_tag, valid_tag))#Defending and common mistakes
- AES-ECB or unauthenticated AES-CBC
- Reusing CTR or GCM nonces
- Naive SHA256(secret + data) MAC
- Comparing MACs with ==
- Textbook RSA or e = 3
- Truncated 24-bit or MD5 hashes
- AEAD: AES-256-GCM or ChaCha20-Poly1305 (or Encrypt-then-MAC)
- Unique 96-bit random or strictly monotonic counter nonce per key
- HMAC-SHA256 or KMAC/SHA-3
- Constant-time hmac.compare_digest()
- RSA-OAEP / RSA-PSS with e = 65537 and >= 2048-bit key
- Full 256-bit SHA-256 or SHA-3 digests
- Masking error messages without fixing the mode: hiding
'padding error'text alone does not stop timing-based padding oracles; use AEAD or Encrypt-then-MAC so tampered ciphertexts are rejected before decryption or unpadding. - Assuming SHA-256 truncation preserves 128-bit collision resistance: collision strength depends strictly on the truncated output length
n, not the internal state size. - Rolling custom crypto in production: stick to vetted high-level libraries (
cryptography,libsodium, TLS 1.3) and review every non-standard construction under CPA/CCA models.
#Summary
- Cryptographic attacks progress from ciphertext-only and known-plaintext to chosen-plaintext (CPA) and chosen-ciphertext (CCA) oracle models.
- ECB leaks block patterns and allows byte-at-a-time CPA recovery, while unauthenticated CBC enables bit-flipping and padding oracles (at most
16 * 256 = 4096queries per block); AEAD (AES-GCM) or Encrypt-then-MAC prevents both. - Stream-cipher nonce reuse exposes
P1 XOR P2, and textbook RSA fails under smalle, common modulus reuse or small private exponentd(Wiener bound). - Birthday attacks collide an
n-bit hash in ~2^(n/2)attempts, naiveSHA256(SECRET || data)falls to length extension, and==comparisons leak timing; defend with full-width SHA-256/SHA-3, HMAC andhmac.compare_digest.