Symmetric Encryption and Block Ciphers Questions
How symmetric-key primitives are constructed and why they work: block-cipher internals (Feistel networks vs substitution-permutation networks, the AES round structure and S-box design, key schedules and why a weak one degrades security), stream ciphers (ChaCha20 and CTR-mode keystream generation), and the internal mechanics of modes of operation (ECB, CBC, CTR, XTS, GCM), including why some are parallelizable, why ECB leaks structure, and why some require a unique nonce. Covers authenticated encryption construction internals (how GHASH and Poly1305 work, why nonce reuse breaks their security algebraically, formal security notions like IND-CPA and INT-CTXT), padding schemes and the mechanics of padding-oracle attacks, and cryptanalysis of block ciphers (differential and linear cryptanalysis, reduced-round attacks). This is the design and internals layer: how these primitives are built and proven secure, distinct from choosing which algorithm or mode to deploy, managing key lifecycle and rotation, or architecting data protection for a system, which belong to the applied cryptography layer.
For AES-GCM using 96-bit random IVs, derive the approximate probability of an IV collision after N messages (use birthday bounds). Compute the safe upper bound for N given an acceptable collision probability of 2^-32, and explain operational implications for a high-throughput service.
Sample Answer
Direct answer
With a 96-bit random initialization vector (IV, the per-message nonce fed into AES-GCM, Advanced Encryption Standard in Galois/Counter Mode), the chance two messages under the same key ever pick the same IV grows with the square of the message count (a birthday-style bound), so it takes roughly 2^32.5, about 6.07 billion, messages under one key before the collision probability reaches 2^-32. NIST (National Institute of Standards and Technology) publishes a rounder, more conservative operational limit of 2^32 invocations per key for exactly this construction, which this derivation reproduces to within a factor of about 1.4.
Structured elaboration
The birthday-bound formula. For N messages drawing uniformly random 96-bit IVs, the probability that at least two of them collide is approximately:
Pcoll(N)≈2⋅296N2=297N2
Intuitively, there are roughly N^2/2 distinct pairs among N draws, and each pair independently has about a 1-in-2^96 chance of colliding, so the total collision probability scales as the square of N over the IV space, not linearly with N. This is the same "birthday paradox" arithmetic behind hash-collision search: doubling the IV space's bit-length does not double the safe message count, it roughly squares it (since N scales as 2 to the power of half the space's bit-length, adjusted for the target probability).
Solving for N. Setting P_coll(N) equal to the target 2^-32 and solving:
N≈2(96+1−32)/2=232.5≈6.07×109
The critical unit-basis check here (a real hazard in this kind of derivation): the exponent 32.5 is the power to raise 2 to, not the message count itself. Writing "N = 32.5" instead of "N = 2^32.5" would be off by roughly nine orders of magnitude and is exactly the kind of exponent-versus-count confusion that makes birthday-bound arithmetic easy to get wrong.
Why GCM cares specifically about random IVs. AES-GCM's confidentiality and its authentication tag both depend on a per-message keystream and hash state derived from the (key, IV) pair. If two messages under the same key ever share an IV, the keystreams collide, which (for GCM specifically) leaks the XOR of the two plaintexts and, because GCM's authentication is built on the same colliding state via GHASH (GCM's universal hash function), also opens a path to forging authentication tags for future messages. So a single IV collision under random-IV GCM is a full break for that pair of messages, not a minor degradation, which is why the safe bound is chosen relative to a very small acceptable probability (2^-32 here) rather than "collision is merely unlikely."
Operational translation. The worked example converts the message-count bound into elapsed time at three plausible throughputs. At 10,000 messages per second, a single key reaches the 2^-32 collision-probability bound in about 7 days; at 100,000 messages per second, under a day. A high-throughput service sharing one key across many encrypting instances needs a key-rotation policy (or a switch to a deterministic/counter-based nonce scheme instead of random IVs) tied to this bound, not to an arbitrary calendar schedule.
Worked example
import math
IV_BITS = 96
TARGET_P = 2 ** -32
# Birthday-bound collision probability after N draws from a space of size 2^IV_BITS:
# P_coll ~= N^2 / (2 * 2^IV_BITS) = N^2 / 2^(IV_BITS+1)
def collision_prob(N, iv_bits=IV_BITS):
return N**2 / (2 ** (iv_bits + 1))
# Solve N^2 / 2^(IV_BITS+1) = TARGET_P = 2^-32
# => N^2 = 2^(IV_BITS+1) * 2^-32 = 2^(IV_BITS+1-32)
# => N = 2^((IV_BITS+1-32) / 2)
exponent = (IV_BITS + 1 - 32) / 2
N = 2 ** exponent
print(f"solved N = 2^{exponent} = {N:.4e}")
# sanity check: plug N back into the collision-probability formula
p_check = collision_prob(N)
print(f"collision_prob(N) = {p_check:.6e} vs target 2^-32 = {TARGET_P:.6e}")
assert abs(math.log2(p_check) - math.log2(TARGET_P)) < 1e-9, "derivation does not reproduce the target"
# operational framing: same basis throughout (N is a per-key MESSAGE COUNT, not a rate)
for rate_per_sec in (1_000, 10_000, 100_000):
seconds_to_N = N / rate_per_sec
days_to_N = seconds_to_N / 86400
print(f"at {rate_per_sec:>7,} msgs/sec -> N reached in {days_to_N:.2f} days "
f"({seconds_to_N:,.0f} s)")
# NIST SP 800-38D's own published operational limit for the random-IV construction
nist_limit = 2 ** 32
print(f"\nNIST SP 800-38D Sec. 8.3 caps random-IV GCM at {nist_limit:.3e} invocations per key "
f"(2^32); our derived exact bound is 2^{exponent} = {N:.3e}, "
f"about {N / nist_limit:.3f}x looser -- NIST's 2^32 is a deliberately rounder, "
f"more conservative number than the exact birthday solution.")
Output:
solved N = 2^32.5 = 6.0740e+09
collision_prob(N) = 2.328306e-10 vs target 2^-32 = 2.328306e-10
at 1,000 msgs/sec -> N reached in 70.30 days (6,074,001 s)
at 10,000 msgs/sec -> N reached in 7.03 days (607,400 s)
at 100,000 msgs/sec -> N reached in 0.70 days (60,740 s)
NIST SP 800-38D Sec. 8.3 caps random-IV GCM at 4.295e+09 invocations per key (2^32); our derived exact bound is 2^32.5 = 6.074e+09, about 1.414x looser -- NIST's 2^32 is a deliberately rounder, more conservative number than the exact birthday solution.
Trade-offs and pitfalls
The exact birthday-derived bound (2^32.5) and NIST's published operational limit (2^32) differ by design, not by error: NIST's 2^32 is deliberately rounder and about 1.4x more conservative, giving margin for the fact that "acceptable collision probability" is itself a policy choice, and that real deployments rarely track invocation counts with perfect precision. Do not treat the exact derived number as the one to enforce in production; treat the published standard's number as the operational ceiling and the derivation as the reasoning that explains where it comes from.
This whole analysis is specific to the random-IV construction. A deterministic construction (a monotonic per-message counter as the nonce, coordinated so no two encrypting processes ever reuse a counter value under the same key) sidesteps the birthday bound entirely, since a counter never repeats by construction; the trade-off moves from "probabilistic collision risk that must be bounded" to "the operational complexity of coordinating a globally unique counter across every process holding the key," which is its own real engineering cost (typically solved with per-instance counter partitions or a centralized nonce-issuing service).
Mixing bases is the most common way to get this kind of estimate wrong in practice: message counts, probability, and bit-lengths of a security parameter are three different units, and an answer that reports "32 bits of safety margin" without saying whether that is an exponent, a probability, or a byte count is not actually a checkable claim.
Summarize AES-SIV (Synthetic IV) mode and its misuse-resistant properties. Explain the S2V construction at a high level, why AES-SIV is deterministic and provides nonce-misuse resistance, and describe scenarios where deterministic encryption is acceptable or desirable (and where it's not).
Sample Answer
Direct answer
AES-SIV (Synthetic Initialization Vector) is a deterministic authenticated-encryption-with-associated-data (AEAD) mode: instead of requiring the caller to supply a fresh nonce, it derives its own internal initialization vector (IV) from the plaintext and associated data (AAD) via a pseudorandom function (PRF) called S2V, then uses that synthetic IV to drive counter (CTR) mode encryption. Because the IV is a deterministic function of the input rather than external randomness, encrypting the exact same (plaintext, AAD) pair twice always produces the exact same ciphertext, and there is no external nonce for a caller to ever accidentally reuse, which is exactly what makes it nonce-misuse-resistant.
Structured elaboration
The S2V construction, at a high level: S2V ("string to vector") takes a vector of inputs, the AAD component(s) followed by the plaintext, and combines them using a cipher-based MAC (CMAC, built from a block cipher) chained together with a "doubling" operation over the finite field GF(2^128) (roughly, multiplying the running value by the field element corresponding to x before XORing in the next component's CMAC), producing a single 128-bit synthetic IV that depends on every input component. That synthetic IV then seeds CTR-mode encryption under a second, independent key.
Why it is deterministic: the whole pipeline, CMAC and the doubling chain, is a pure function of its inputs and the key; there is no randomness or external nonce anywhere in it. The same (AAD, plaintext) under the same key always produces the same synthetic IV, and CTR mode with the same IV under the same key always produces the same keystream, so the ciphertext is identical every time.
Why that provides nonce-misuse resistance: traditional nonce-based modes like Galois/Counter Mode (GCM) derive their security proof from the nonce never repeating; if a caller ever reuses a GCM nonce, the scheme's confidentiality and authenticity guarantees both collapse (the keystream repeats, directly leaking the plaintext XOR, and the authentication key's internal state becomes solvable). SIV sidesteps the entire failure category by removing the external nonce as an attack surface: there is nothing for a caller to misuse, because SIV never asks for it.
Where determinism is acceptable, and where it is not: deterministic encryption is desirable when the caller cannot guarantee fresh, unique randomness (embedded devices with weak boot entropy, storage/deduplication systems that specifically want equal records to look equal so they can be deduplicated) or where messages are inherently unique enough that repeats are not sensitive (each message includes a unique ID as AAD, for instance). It is undesirable whenever equal-looking ciphertext for equal plaintext is itself sensitive information, for example authenticating a small, low-entropy field (a yes/no flag, a status code) where an observer who sees two identical ciphertexts learns the two underlying values were equal, without ever decrypting either.
Worked example
from cryptography.hazmat.primitives.ciphers.aead import AESSIV
key = AESSIV.generate_key(bit_length=256) # split into two independent 128-bit subkeys
siv = AESSIV(key)
pt = b"invoice #4471: $250.00"
ct_a = siv.encrypt(pt, [b"customer:118"])
ct_b = siv.encrypt(pt, [b"customer:118"])
print("same (plaintext, AAD), no nonce supplied, twice:")
print(" identical ciphertext (deterministic):", ct_a == ct_b)
ct_c = siv.encrypt(b"invoice #4471: $250.01", [b"customer:118"]) # one cent different
print(" different plaintext -> different ciphertext:", ct_c != ct_a)
ct_d = siv.encrypt(pt, [b"customer:999"]) # different AAD, same plaintext
print(" different AAD, same plaintext -> different ciphertext:", ct_d != ct_a)
Output:
same (plaintext, AAD), no nonce supplied, twice:
identical ciphertext (deterministic): True
different plaintext -> different ciphertext: True
different AAD, same plaintext -> different ciphertext: True
This confirms the two claims directly: identical inputs give identical output (the determinism the S2V construction guarantees), and any change to either the plaintext or the AAD (both are inputs to S2V's chain) changes the ciphertext, since a different input to a PRF-based chain produces, with overwhelming probability, a different synthetic IV.
Trade-offs and pitfalls
The most common mistake is describing SIV as "just GCM but safer" without naming the actual price paid: determinism intentionally reveals equality of (AAD, plaintext) pairs, a strictly different (and for some applications unacceptable) leak profile from GCM's nonce-reuse failure mode, which leaks plaintext XOR and can enable full forgery, a much more severe but avoidable failure if nonces are managed correctly. Second, SIV requires buffering the entire plaintext before encryption can begin (S2V has to process the whole message to produce the synthetic IV before CTR mode can start), which makes it unsuitable for streaming very large or unbounded messages the way a nonce-based streaming AEAD can handle; SIV is a better fit for whole, bounded messages (key wrapping, records, small documents) than for high-throughput streaming pipelines. Finally, the two internal keys (the CMAC key for S2V, and the CTR encryption key) must be cryptographically independent for the security proof to hold; a real implementation should never derive them from each other or from any related process.
Given a black-box encryption oracle for a 128-bit-block block cipher under a fixed unknown key, design a testing methodology to detect weak keys, keyed-collisions, and susceptibility to slide or related-key structural attacks. Describe the chosen-plaintext sets, statistical tests to run, how to interpret results, and rough complexity estimates.
Sample Answer
Direct answer
Run a battery of statistical distinguishers against the oracle at increasing structural specificity: start with a generic randomness check (does flipping one input bit change roughly half the output bits, as an ideal permutation would), then a chosen-difference test (does a fixed input XOR pattern produce any output XOR value far more often than the roughly 2^-128 baseline a random 128-bit permutation would give), then structural probes shaped specifically for slide-style self-similarity in the key schedule. A single fixed unknown key fundamentally cannot support a true related-key test, since that needs oracle access under multiple related keys, so the methodology has to be explicit about that gap rather than quietly treating a single-key battery as if it covered related-key attacks too.
Structured elaboration
Setup. A black-box oracle E_K(.) for a 128-bit-block cipher under one fixed, unknown key K. Three things to detect: weak keys (keys under which the cipher behaves non-randomly, often from a degenerate key schedule), keyed collisions (a meaningful signal only because a true block cipher is a bijection, a one-to-one mapping, so any exact output collision among distinct inputs is itself direct evidence of a broken permutation, not merely an unlikely event), and susceptibility to slide or related-key structural attacks.
Chosen-plaintext sets.
- Random pairs, single-bit flip: sample N random 128-bit plaintexts, flip one random bit in each to get a paired plaintext, submit both to the oracle, and measure the Hamming distance (the number of differing bits) between the two ciphertexts. This is the avalanche test.
- Fixed-delta differential sets: fix an input XOR difference
delta, sample many random plaintext pairs that differ by exactly that value, and collect the output XOR for each pair. Looking at the distribution of output-XOR values across trials, any value occurring far above the roughly-1-expected-occurrence baseline (since trials are vastly fewer than 2^128) is evidence of an exploitable differential characteristic at roughly that probability. - Slide-probe sets: a slide attack exploits a self-similar, often periodic or otherwise degenerate, key schedule. If the cipher's round-function structure is known from a public specification, choose plaintext pairs related by that round function and check whether ciphertext pairs preserve the same relation. Against a truly opaque black box, where even the structure, not just the key, is unknown, this degenerates to a weaker generic test: look for any small set of plaintexts whose relative ciphertext behavior is anomalously self-consistent compared to fresh random plaintexts, since a short or repeating effective key schedule reduces the number of independent rounds and should show up as reduced diffusion relative to the full expected round count.
Statistical tests and how to interpret them. Avalanche mean and standard deviation compared to the ideal: a 128-bit block's mean Hamming distance should sit near 64 bits with a small spread; the worked example measures mean 64.13 and standard deviation 5.71 over 2000 trials against real, unweakened AES, which is itself a useful reference distribution to compare a suspect cipher against. For the differential test, the expected count of the single most frequent output-XOR value under an ideal permutation, with trial count far below 2^128, is about 1, no meaningful repeats; a cipher showing a value repeating roughly trials/2^k times is evidence of an approximate probability-2^-k differential, and differential cryptanalysis becomes practical once k is small enough that on the order of 2^k chosen-plaintext pairs is a realistic query budget, not merely because a nonzero bias exists at all (every real block cipher has some nonzero best-differential probability; the question is whether it is small enough to matter).
Correct complexity basis. A generic collision search over an n-bit output space needs about:
queries≈2n/2,n=128 ⇒ 264≈1.8×1019
not "n/2 queries." Dividing the bit-length by two divides the exponent, not the raw query count, exactly the confusion that would understate the real cost by nineteen orders of magnitude if written down carelessly.
Rough complexity estimates. Avalanche and differential screening are cheap: a few thousand to tens of thousands of queries give strong signal for gross structural weaknesses, as the worked example's 2000- and 20,000-trial tests show. Confirming a specific differential's exact probability precisely enough to distinguish a 2^-128 baseline from, say, a 2^-100 weakness would need on the order of 2^100 trials, infeasible. So in practice a screening battery is a first pass that flags suspicious deltas cheaply, and only deltas with an anomalously high observed count, even from a modest trial count, merit a deeper, targeted follow-up with a much larger trial budget focused on just that delta.
Worked example
import os
import random
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
# The "black-box oracle": single 128-bit-block encryption under one FIXED unknown key.
# We stand this up with real AES (single ECB block = the raw block-cipher permutation,
# not used as a communications mode) purely so the statistical tests below run against
# a genuine, reproducible 128-bit block permutation.
_rng = random.Random(20260901)
_fixed_key = bytes(_rng.randrange(256) for _ in range(16))
_enc_ctx = Cipher(algorithms.AES(_fixed_key), modes.ECB()).encryptor()
def oracle(block16: bytes) -> bytes:
# Fresh encryptor per call: ECB mode object is stateful update()/finalize(), so we
# rebuild it for each independent 16-byte query to the "oracle".
enc = Cipher(algorithms.AES(_fixed_key), modes.ECB()).encryptor()
return enc.update(block16) + enc.finalize()
def hamming(a: bytes, b: bytes) -> int:
return sum(bin(x ^ y).count("1") for x, y in zip(a, b))
# --- Avalanche test: flip one input bit, measure output Hamming distance.
# Expectation under a good 128-bit block cipher: mean ~64/128 bits flip, std small. ---
rng = random.Random(1) # pinned seed for reproducibility
N_AVALANCHE = 2000
distances = []
for _ in range(N_AVALANCHE):
p = bytes(rng.randrange(256) for _ in range(16))
bit = rng.randrange(128)
p2 = bytearray(p)
p2[bit // 8] ^= (1 << (bit % 8))
c1, c2 = oracle(p), oracle(bytes(p2))
distances.append(hamming(c1, c2))
mean_d = sum(distances) / len(distances)
var_d = sum((d - mean_d) ** 2 for d in distances) / len(distances)
print(f"avalanche over {N_AVALANCHE} single-bit-flip pairs: mean={mean_d:.2f} bits "
f"(ideal 64.0), stdev={var_d**0.5:.2f}")
# --- Differential test: fixed input XOR delta, look for an output-XOR that occurs far
# more often than the ~2^-128 baseline expected for a random permutation. ---
def diff_test(delta: bytes, trials: int):
from collections import Counter
counts = Counter()
for _ in range(trials):
p = bytes(rng.randrange(256) for _ in range(16))
p2 = bytes(x ^ y for x, y in zip(p, delta))
c1, c2 = oracle(p), oracle(p2)
out_xor = bytes(x ^ y for x, y in zip(c1, c2))
counts[out_xor] += 1
most_common_count = counts.most_common(1)[0][1]
return most_common_count, trials
delta = bytes([0x01] + [0] * 15) # single-bit input difference
most_common_count, trials = diff_test(delta, 20_000)
print(f"differential test, delta=0x01000...0, {trials} trials: "
f"most frequent output-XOR appeared {most_common_count} time(s) "
f"(baseline expectation ~1 with 2^-128 bias, {trials} << 2^128 so no repeat is expected "
f"for a strong cipher; a value repeating ~trials/2^k times would indicate an effective "
f"differential bias around 2^-k)")
# --- Complexity estimate, done correctly on a BIRTHDAY basis, not a linear one ---
# A generic collision search over a 128-bit output space needs about 2^(128/2) = 2^64
# queries (birthday bound), NOT 2^(128/2)=64 queries. Show the two numbers side by side
# to make the units-basis explicit.
n_bits = 128
linear_half = n_bits / 2 # WRONG basis if used as an exponent value directly
birthday_queries_log2 = n_bits / 2 # correct EXPONENT: queries ~= 2^(n/2)
print(f"block size n={n_bits} bits -> generic collision search needs about "
f"2^{birthday_queries_log2:.0f} queries (~1.8e19), "
f"NOT '{linear_half:.0f} queries' -- the /2 divides the EXPONENT, not the query count itself")
Output:
avalanche over 2000 single-bit-flip pairs: mean=64.13 bits (ideal 64.0), stdev=5.71
differential test, delta=0x01000...0, 20000 trials: most frequent output-XOR appeared 1 time(s) (baseline expectation ~1 with 2^-128 bias, 20000 << 2^128 so no repeat is expected for a strong cipher; a value repeating ~trials/2^k times would indicate an effective differential bias around 2^-k)
block size n=128 bits -> generic collision search needs about 2^64 queries (~1.8e19), NOT '64 queries' -- the /2 divides the EXPONENT, not the query count itself
Trade-offs and pitfalls
False negatives are the default outcome of this methodology, not a rare exception: a feasible trial count, thousands to low millions of queries, can only catch gross structural weaknesses. A cipher with a subtle differential at probability 2^-40, still catastrophic for a real deployment doing more than 2^40 encryptions under one key, is statistically invisible to a 20,000-trial screen and needs a much larger, targeted trial budget once some hint, from cipher design, code review, or a suspicious delta, narrows the search.
Related-key attacks are genuinely out of reach for a truly single-fixed-key oracle. This methodology can surface structural symptoms consistent with a weak key schedule, reduced diffusion, slide-like self-consistency, but it cannot directly confirm a related-key differential, which needs oracle access under multiple related keys. State that limitation explicitly rather than presenting the single-key battery as a complete answer to the related-key part of the question.
A true collision, an exact ciphertext match between two distinct plaintexts, should have probability zero for a genuine bijective block cipher. Observing even one exact collision among a modest number of queries, well under the roughly 2^64 birthday bound for a 128-bit block, is a stronger and far cheaper signal than any statistical distribution test above, since it proves non-bijectivity outright rather than merely shifting a probability estimate; it is worth running as a cheap standing check on every query pair regardless of what the other tests find.
Explain how Associated Data length and ciphertext length are incorporated into GCM's GHASH computation (including padding behavior). Describe what happens if an implementation incorrectly pads or omits the length block and how that affects tag verification.
Sample Answer
Direct answer
GHASH, GCM's (Galois/Counter Mode) internal universal hash function, processes the associated data (AAD, additional authenticated data carried alongside the ciphertext) and the ciphertext as a sequence of 128-bit blocks, each independently zero-padded to a full block if its last partial block is short, and then ingests exactly one more special block containing the bit-length of the AAD and the bit-length of the ciphertext, each a 64-bit big-endian integer, concatenated into that final 128-bit block. Omitting that length block, or corrupting it, changes GHASH's output and therefore the authentication tag, so a buggy implementation that drops or miscomputes it will simply fail to interoperate, legitimate messages get rejected. The more serious consequence is security, not just correctness: without the length block, GHASH cannot tell where the AAD ends and the ciphertext begins, which opens a genuine forgery by relabeling which bytes count as which, demonstrated below.
Structured elaboration
GHASH's block structure. Let A be the AAD and C be the ciphertext. Each is independently padded with zero bytes up to a multiple of 128 bits, then split into 16-byte blocks A_1..A_m and C_1..C_n. GHASH processes the sequence [A_1, ..., A_m, C_1, ..., C_n, L], where L is the length block, using the recurrence:
Y0=0128,Yi=(Yi−1⊕Xi)⋅H in GF(2128)
Here GF(2^128) is a Galois Field, a finite-field arithmetic system with 2^128 elements, used with the reduction polynomial:
x128+x7+x2+x+1
and H = E_K(0^128), the block cipher encrypting an all-zero block under the session key, is GHASH's "hash subkey." The final block fed in is:
Xblocks=[A1,…,Am, C1,…,Cn, len(A)64∥len(C)64]
Two distinct failure modes.
- Length block omitted entirely. GHASH becomes a hash of just the concatenated, padded block sequence, with no information about where the AAD/ciphertext boundary falls. Because each of A and C is padded to a whole-block multiple before concatenation, a boundary shift that lines up on a block boundary produces the exact same sequence of blocks whether those blocks are labeled "the last block of A plus all of C" or "part of A extended further, and only the remaining blocks are C." GHASH cannot distinguish the two labelings, since it never sees where one field ends and the next begins.
- Length fields swapped or otherwise corrupted. A buggy implementation that puts len(C) where len(A) belongs, and vice versa, computes a different, wrong length block on both the sender and an independent verifier using a correct implementation, so the tag will not match and the message is rejected. This is a plain interoperability bug, an availability problem, not by itself a security hole, unless the same swap is made consistently by both a broken sender and a broken verifier, in which case the two broken instances simply become a non-standard, non-interoperable variant that should not be considered "GCM" for the purposes of any security proof relying on the real algorithm.
Why omission is the more serious failure mode. The first worked example below confirms the tag differs the moment the length block is omitted or the two length fields are swapped, matching failure mode 2. The second worked example demonstrates failure mode 1 as an actual, executed forgery: two different (AAD, ciphertext) labelings of the identical wire bytes produce an identical GHASH output, and therefore an identical valid tag, under a GHASH implementation missing the length block; the real, length-block-including construction produces two different tags for the same relabeling attempt, closing the gap.
Worked example
Implementation check against the trusted library, plus the length-block-omitted and length-swapped correctness checks:
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
def aes_block_encrypt(key: bytes, block16: bytes) -> bytes:
enc = Cipher(algorithms.AES(key), modes.ECB()).encryptor()
return enc.update(block16) + enc.finalize()
def gf128_mul(x: bytes, y: bytes) -> bytes:
# GCM's GF(2^128) multiply, reduction polynomial x^128+x^7+x^2+x+1,
# reflected bit convention (leftmost bit of the block = coefficient of x^0).
x_int = int.from_bytes(x, "big")
y_int = int.from_bytes(y, "big")
R = 0xE1 << 120
MASK = (1 << 128) - 1
z = 0
v = x_int
for i in range(128):
bit = (y_int >> (127 - i)) & 1
if bit:
z ^= v
lsb = v & 1
v >>= 1
if lsb:
v ^= R
v &= MASK
return z.to_bytes(16, "big")
def pad16(b: bytes) -> bytes:
r = len(b) % 16
return b if r == 0 else b + b"\x00" * (16 - r)
def ghash(H: bytes, aad: bytes, ct: bytes, *, len_block: bytes = None) -> bytes:
blocks = []
ap, cp = pad16(aad), pad16(ct)
blocks += [ap[i:i+16] for i in range(0, len(ap), 16)] if ap else []
blocks += [cp[i:i+16] for i in range(0, len(cp), 16)] if cp else []
if len_block is None:
len_block = (len(aad) * 8).to_bytes(8, "big") + (len(ct) * 8).to_bytes(8, "big")
blocks.append(len_block)
Y = b"\x00" * 16
for X in blocks:
Y = bytes(a ^ b for a, b in zip(Y, X))
Y = gf128_mul(Y, H)
return Y
def inc32(block: bytes) -> bytes:
counter = (int.from_bytes(block[-4:], "big") + 1) & 0xFFFFFFFF
return block[:-4] + counter.to_bytes(4, "big")
def gctr(key: bytes, icb: bytes, data: bytes) -> bytes:
if not data:
return b""
out = bytearray()
cb = icb
for i in range(0, len(data), 16):
chunk = data[i:i+16]
ks = aes_block_encrypt(key, cb)
out.extend(a ^ b for a, b in zip(chunk, ks[:len(chunk)]))
cb = inc32(cb)
return bytes(out)
def gcm_encrypt(key: bytes, iv12: bytes, plaintext: bytes, aad: bytes, tag_len=16, *, bad_len_block=None):
H = aes_block_encrypt(key, b"\x00" * 16)
J0 = iv12 + b"\x00\x00\x00\x01"
ct = gctr(key, inc32(J0), plaintext)
S = ghash(H, aad, ct, len_block=bad_len_block)
T = gctr(key, J0, S)[:tag_len]
return ct, T
# --- reproducibility: pinned key/nonce/plaintext/AAD ---
key = bytes(range(16)) # AES-128
iv = bytes(range(12)) # 96-bit nonce
plaintext = b"the quick brown fox jumps over the lazy dog!!!!" # 48 bytes = 3 blocks
aad = b"header:v1;stream=42" # 20 bytes = 2 padded blocks
# 1) from-scratch GCM vs the trusted library implementation
ct_mine, tag_mine = gcm_encrypt(key, iv, plaintext, aad)
lib_out = AESGCM(key).encrypt(iv, plaintext, aad)
lib_ct, lib_tag = lib_out[:-16], lib_out[-16:]
print("ciphertext matches library:", ct_mine == lib_ct)
print("tag matches library: ", tag_mine == lib_tag)
print("tag (hex):", tag_mine.hex())
# 2) what happens if the length block is OMITTED (GHASH run without appending it)?
H = aes_block_encrypt(key, b"\x00" * 16)
J0 = iv + b"\x00\x00\x00\x01"
def ghash_no_len_block(H, aad, ct):
blocks = []
ap, cp = pad16(aad), pad16(ct)
blocks += [ap[i:i+16] for i in range(0, len(ap), 16)]
blocks += [cp[i:i+16] for i in range(0, len(cp), 16)]
# deliberately NOT appending the length block
Y = b"\x00" * 16
for X in blocks:
Y = bytes(a ^ b for a, b in zip(Y, X))
Y = gf128_mul(Y, H)
return Y
S_missing = ghash_no_len_block(H, aad, ct_mine)
tag_missing_len = gctr(key, J0, S_missing)[:16]
print("tag with length block OMITTED:", tag_missing_len.hex())
print("differs from correct tag:", tag_missing_len != tag_mine)
# 3) what happens if AAD length and ciphertext length are SWAPPED in the length block
# (a real implementation bug: putting len(C) where len(A) goes and vice versa)?
wrong_len_block = (len(plaintext) * 8).to_bytes(8, "big") + (len(aad) * 8).to_bytes(8, "big")
_, tag_swapped = gcm_encrypt(key, iv, plaintext, aad, bad_len_block=wrong_len_block)
print("tag with AAD/CT lengths swapped:", tag_swapped.hex())
print("differs from correct tag:", tag_swapped != tag_mine)
# 4) confirm the RECEIVER side genuinely rejects a correctly-shaped ciphertext when
# verified with the WRONG (buggy) tag, using the real library as the verifier
try:
AESGCM(key).decrypt(iv, ct_mine + tag_missing_len, aad)
print("VERIFICATION WRONGLY ACCEPTED (bug)")
except Exception as e:
print("library correctly rejects the mis-computed tag:", type(e).__name__)
Output:
ciphertext matches library: True
tag matches library: True
tag (hex): 1036a15c78d0d430caa1c69ba0bb8c3a
tag with length block OMITTED: bdcff991b0b06971ab030c30acce9dca
differs from correct tag: True
tag with AAD/CT lengths swapped: 3f246b19417b553075acb43c3bd5183d
differs from correct tag: True
library correctly rejects the mis-computed tag: InvalidTag
The forgery this omission actually enables, relabeling which wire bytes count as AAD versus ciphertext without changing the tag:
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
def aes_block_encrypt(key, block16):
enc = Cipher(algorithms.AES(key), modes.ECB()).encryptor()
return enc.update(block16) + enc.finalize()
def gf128_mul(x, y):
x_int = int.from_bytes(x, "big"); y_int = int.from_bytes(y, "big")
R = 0xE1 << 120; MASK = (1 << 128) - 1
z = 0; v = x_int
for i in range(128):
bit = (y_int >> (127 - i)) & 1
if bit: z ^= v
lsb = v & 1
v >>= 1
if lsb: v ^= R
v &= MASK
return z.to_bytes(16, "big")
def pad16(b):
r = len(b) % 16
return b if r == 0 else b + b"\x00" * (16 - r)
def blocks_of(aad, ct):
bl = [pad16(aad)[i:i+16] for i in range(0, len(pad16(aad)), 16)] if aad else []
bl += [pad16(ct)[i:i+16] for i in range(0, len(pad16(ct)), 16)] if ct else []
return bl
def ghash_no_len(H, aad, ct):
Y = b"\x00" * 16
for X in blocks_of(aad, ct):
Y = bytes(a ^ b for a, b in zip(Y, X)); Y = gf128_mul(Y, H)
return Y
def ghash_with_len(H, aad, ct):
Y = b"\x00" * 16
bl = blocks_of(aad, ct)
bl.append((len(aad) * 8).to_bytes(8, "big") + (len(ct) * 8).to_bytes(8, "big"))
for X in bl:
Y = bytes(a ^ b for a, b in zip(Y, X)); Y = gf128_mul(Y, H)
return Y
def inc32(block):
counter = (int.from_bytes(block[-4:], "big") + 1) & 0xFFFFFFFF
return block[:-4] + counter.to_bytes(4, "big")
def gctr(key, icb, data):
if not data: return b""
out = bytearray(); cb = icb
for i in range(0, len(data), 16):
chunk = data[i:i+16]
ks = aes_block_encrypt(key, cb)
out.extend(a ^ b for a, b in zip(chunk, ks[:len(chunk)]))
cb = inc32(cb)
return bytes(out)
key = bytes(range(16))
H = aes_block_encrypt(key, b"\x00" * 16)
iv = bytes(range(12))
J0 = iv + b"\x00\x00\x00\x01"
# --- Legitimate sender: AAD = 16-byte header, ciphertext = 32-byte body ---
A = b"AAAAAAAAAAAAAAAA" # 16-byte AAD
P = b"CCCCCCCCCCCCCCCC" + b"DDDDDDDDDDDDDDDD" # 32-byte plaintext body
ct_wire = gctr(key, inc32(J0), P) # 32 ciphertext bytes actually sent on the wire
S_legit_nolen = ghash_no_len(H, A, ct_wire)
tag_legit_nolen = gctr(key, J0, S_legit_nolen)[:16]
print(f"legit: AAD={len(A)}B ciphertext={len(ct_wire)}B tag={tag_legit_nolen.hex()}")
# --- Attacker relabels the SAME wire bytes: first 16 ciphertext bytes are claimed as
# AAD instead, only the remaining 16 are claimed as ciphertext. Same 3-block
# sequence [A, ct_wire[0:16], ct_wire[16:32]] fed to GHASH either way. ---
A_forged = A + ct_wire[0:16] # 32-byte "AAD" (attacker's claim)
ct_forged = ct_wire[16:32] # 16-byte "ciphertext" (attacker's claim)
S_forged_nolen = ghash_no_len(H, A_forged, ct_forged)
tag_forged_nolen = gctr(key, J0, S_forged_nolen)[:16]
print(f"forged: AAD={len(A_forged)}B ciphertext={len(ct_forged)}B tag={tag_forged_nolen.hex()}")
print("NO-LENGTH-BLOCK GHASH: forged relabeling produces the SAME tag (a real forgery):",
tag_forged_nolen == tag_legit_nolen)
# --- Same relabeling attempt against the REAL length-block-including construction ---
S_legit_len = ghash_with_len(H, A, ct_wire)
tag_legit_len = gctr(key, J0, S_legit_len)[:16]
S_forged_len = ghash_with_len(H, A_forged, ct_forged)
tag_forged_len = gctr(key, J0, S_forged_len)[:16]
print(f"with length block, legit tag={tag_legit_len.hex()} forged-relabel tag={tag_forged_len.hex()}")
print("WITH-LENGTH-BLOCK GHASH: forged relabeling produces the SAME tag:",
tag_forged_len == tag_legit_len, "(length binding defeats the relabeling)")
Output:
legit: AAD=16B ciphertext=32B tag=b440a4522b071693b27c389b21f6a6c5
forged: AAD=32B ciphertext=16B tag=b440a4522b071693b27c389b21f6a6c5
NO-LENGTH-BLOCK GHASH: forged relabeling produces the SAME tag (a real forgery): True
with length block, legit tag=e7824e94badbade189acc757175e965c forged-relabel tag=c13fec6f71adacb445a2057ba1862cf0
WITH-LENGTH-BLOCK GHASH: forged relabeling produces the SAME tag: False (length binding defeats the relabeling)
Trade-offs and pitfalls
AAD and ciphertext are padded separately, each to its own block boundary, before concatenation, not padded once as a single combined blob. Padding the concatenation as one blob would introduce an even worse, sub-block-level ambiguity, since a short AAD and a short ciphertext could then be indistinguishable at the byte level, not just at whole-block boundaries. Padding each field independently limits the boundary ambiguity strictly to whole-block shifts, which is exactly the residual gap the length block then closes completely.
Any implementation of GCM, or a mode built on the same universal-hash-plus-length-block pattern, needs the length encoding tested explicitly, not just assumed correct because the ciphertext round-trips: a swapped or dropped length field can silently pass a naive "does encrypt-then-decrypt give back the plaintext" self-test if both sides share the same bug, which is exactly why an independent, correct reference implementation matters for catching this class of defect, as the worked example's cross-check against the trusted library does.
Formal treatments of GCM frame this as a domain-separation problem, the same general class of issue that motivates length-prefixing in other constructions, such as guarding against related length-extension or boundary-confusion issues in some MAC (message authentication code) designs; the specific mechanism differs by construction, but the underlying principle, that a variable-length input needs its own length cryptographically bound in, not merely implied by where the bytes happen to stop, recurs across authenticated-hashing designs generally.
Explain why Electronic Codebook (ECB) mode is insecure for encrypting structured or repetitive data. Provide a concrete adversarial example showing how identical plaintext blocks yield identical ciphertext blocks and how this leaks structure, and propose practical alternatives (modes or constructions) to ECB for both file encryption and network protocols.
Sample Answer
Direct answer
Electronic Codebook (ECB) mode encrypts a message by splitting it into fixed-size blocks (16 bytes for AES) and running the block cipher independently on each block with no chaining between blocks. Because encryption is deterministic (the same block cipher, the same key), two identical plaintext blocks always produce two identical ciphertext blocks. Any repetition or structure in the plaintext (a repeated header, a solid-colored region of an image, padding bytes) shows up as repetition in the ciphertext, which leaks information about the plaintext's shape even though the attacker cannot read its content.
Structured elaboration
Why this happens mechanically. AES (Advanced Encryption Standard, the standard 128-bit block cipher) is a keyed permutation: AES_K(block) is a pure function of block and the key K, with no other input. ECB calls that function once per block:
C_1 = AES_K(P_1)
C_2 = AES_K(P_2)
...
If P_i == P_j for any two blocks, then C_i == C_j follows directly, because the function has no state carried between calls and no per-block randomness (no initialization vector, or IV, the per-message random value that other modes mix in to break this determinism).
Why this is a real security failure, not a cosmetic one. Confidentiality is usually defined so that ciphertext must reveal nothing about the plaintext beyond its length. ECB fails this even when the key is never touched: an attacker who never learns a single plaintext bit can still recover the plaintext's layout (which rows of an image are identical, which fields of a record repeat, where a repeating cipher-block pattern starts and ends), and layout alone is often enough to break a system (e.g. detecting which of several form fields hold a known default value, or which video frames are near-duplicates of the previous frame).
Worked example
Encrypting a 64-byte, 4-block message under a fixed AES-128 key, where blocks 1, 2, and 4 are the identical text STATUS:OK------- and block 3 is different:
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
key = bytes.fromhex("000102030405060708090a0b0c0d0e0f")
plaintext = (
b"STATUS:OK-------" + # block 1
b"STATUS:OK-------" + # block 2 (identical to block 1)
b"STATUS:FAIL-----" + # block 3 (different)
b"STATUS:OK-------" # block 4 (identical to blocks 1 and 2)
)
cipher = Cipher(algorithms.AES(key), modes.ECB())
enc = cipher.encryptor()
ct = enc.update(plaintext) + enc.finalize()
blocks = [ct[i:i+16] for i in range(0, len(ct), 16)]
for i, b in enumerate(blocks, 1):
print(f"ciphertext block {i}: {b.hex()}")
print("block 1 == block 2 :", blocks[0] == blocks[1])
print("block 1 == block 4 :", blocks[0] == blocks[3])
print("block 1 == block 3 :", blocks[0] == blocks[2])
Output:
ciphertext block 1: 6057c69d895843836ab01c6f792fc526
ciphertext block 2: 6057c69d895843836ab01c6f792fc526
ciphertext block 3: 1a02ed1c6c42ebe7cd763ece640c1adb
ciphertext block 4: 6057c69d895843836ab01c6f792fc526
block 1 == block 2 : True
block 1 == block 4 : True
block 1 == block 3 : False
An adversary who never sees the key can still read off, purely from ciphertext, that records 1, 2, and 4 hold the same value and record 3 holds something different. This is the exact mechanism behind the well-known "ECB penguin" image: encrypting a bitmap in ECB leaves flat-colored regions visibly intact in the ciphertext, because repeated pixel blocks map to repeated ciphertext blocks.
Practical alternatives.
- File and disk encryption: use an authenticated mode: AES-GCM (Galois/Counter Mode) or ChaCha20-Poly1305, both AEAD (Authenticated Encryption with Associated Data) constructions that add semantic-security-breaking randomness (a nonce, a value used only once per key) per message or per chunk, plus a MAC (message authentication code) that also detects tampering, something ECB never provided even when used "correctly."
- Network protocols: TLS (Transport Layer Security) and SSH use AEAD ciphersuites (AES-GCM or ChaCha20-Poly1305) with a fresh nonce derived per record from the connection's sequence number, so no two records under the same key ever reuse the same keystream, and repeated plaintext structure (HTTP headers repeating across requests, for example) no longer produces repeated ciphertext.
Trade-offs and pitfalls
- ECB has no legitimate general-purpose use for structured or repetitive data; it survives in some legacy code and in certain narrow contexts (encrypting single independent, high-entropy, fixed-format blocks like some key-wrapping schemes) where the "no chaining" property is deliberately wanted, but that is the exception, not the rule.
- Switching to CBC (Cipher Block Chaining) alone is not sufficient if the IV is reused or predictable; the fix is authenticated encryption with a unique nonce per message, not just "not ECB."
- A common mistake is assuming compression or padding hides the pattern; it does not, since the pattern is visible at the block-alignment level regardless of what the plaintext bytes semantically mean.
Unlock Full Question Bank
Get access to all 46 Symmetric Encryption and Block Ciphers interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.