Skip to main content
Cryptographic Attack Models and Implementation Failures
Lesson 1 of 3

Cryptographic Attack Models and Implementation Failures

Classify cryptographic attack models (CPA/CCA), analyze block-mode, nonce-reuse, weak-RSA, hash-extension and timing failures in safe CTF labs, and implement AEAD, HMAC and constant-time defenses.

Advanced 30 min Cryptography

Learning objectives

  • Classify ciphertext-only, known-plaintext, chosen-plaintext (CPA) and chosen-ciphertext (CCA) attack models
  • Explain why ECB block patterns, CBC bit-flipping and CBC padding oracles break unauthenticated encryption
  • Analyze stream-cipher nonce reuse and weak RSA parameter choices (small e, common modulus, Wiener bound)
  • Explain birthday collisions, Merkle-Damgard hash length extension and timing side-channels
  • Replace vulnerable constructions with AEAD (AES-GCM), HMAC-SHA256 and constant-time comparison

Recommended first: Symmetric Encryption: AES, Block Modes & AEADAsymmetric Cryptography: RSA, Diffie-Hellman & ECCCryptographic Hashing, Password KDFs & HMACMessage Authentication Codes (HMAC) & IntegrityDigital Signatures: RSA-PSS, ECDSA & Ed25519

#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:

  1. Ciphertext-Only (COA)Attacker sees only ciphertexts; relies on frequency analysis or weak keys
  2. Known-Plaintext (KPA)Attacker holds fixed (plaintext, ciphertext) pairs such as known headers
  3. Chosen-Plaintext (CPA)Attacker queries an encryption oracle on arbitrary chosen plaintexts
  4. 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], where I[i] = AES_dec(K, C[i]) is the intermediate block. Flipping a bit in C[i-1] flips the exact same bit in P[i] (while scrambling P[i-1]), letting an attacker alter structured fields like role=user if 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 value pad_val for a modified previous byte guess, the equation I[i][j] XOR guess == pad_val holds, revealing the intermediate byte I[i][j] = guess XOR pad_val and then the original plaintext byte P[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 most 16 * 256 = 4096 queries 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 = 3 and a short message satisfies m^3 < n, modular reduction never occurs, so taking the ordinary integer cube root of c recovers m instantly.
  • Common modulus reuse: encrypting the same message m under the same modulus n with two coprime exponents e1 and e2 lets an observer combine the ciphertexts using the Extended Euclidean Algorithm (a*e1 + b*e2 = 1) to recover m without factoring n.
  • Wiener's attack bound: choosing a tiny private exponent d < (1/3) * n^(1/4) to speed up decryption allows d to be recovered efficiently via continued fractions of e / 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.

Safe lab demo: birthday bound, nonce-reuse XOR cancellation, and HMAC defense
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

Vulnerable Constructions vs Defensive Replacements
Vulnerable Practice
  • 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
Defensive Replacement
  • 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 = 4096 queries per block); AEAD (AES-GCM) or Encrypt-then-MAC prevents both.
  • Stream-cipher nonce reuse exposes P1 XOR P2, and textbook RSA fails under small e, common modulus reuse or small private exponent d (Wiener bound).
  • Birthday attacks collide an n-bit hash in ~2^(n/2) attempts, naive SHA256(SECRET || data) falls to length extension, and == comparisons leak timing; defend with full-width SHA-256/SHA-3, HMAC and hmac.compare_digest.

Lecture presentations

Slides on this topic: view them in the browser or download the PDF.

Knowledge check

Sign in to take the test, complete lessons and save your progress. Log in

Practice: test your knowledge