Cryptography Fundamentals Questions
Core concepts and vocabulary of cryptography: confidentiality, integrity, authentication, and non-repudiation; the difference between symmetric and asymmetric primitives; and how standard algorithms, libraries, and protocols fit together. Covers threat models, common standards, and applying primitives and cryptographic libraries correctly to real-world security problems. The entry point for the cryptography track.
Define initialization vector (IV) and nonce as used in block/stream cipher modes. What properties must each satisfy (randomness vs uniqueness), and what happens in practice if a nonce is reused with a mode like GCM?
Sample Answer
Direct answer
An initialization vector (IV) or nonce ("number used once") is extra, non-secret input
combined with the key so that encrypting the same plaintext twice under the same key does not
produce the same ciphertext twice. Different cipher modes need different properties from it:
some need it unpredictable, all of them need it to never repeat under the same key. Reusing a
nonce with GCM is not a minor bug, it is a full break of that key's confidentiality and
authenticity.
Structured elaboration
- CBC mode: the IV should be unpredictable (ideally generated by a CSPRNG) and must never
repeat under the same key. It does not need to be secret, it is normally sent alongside the
ciphertext. - CTR and GCM modes: the nonce's essential property is uniqueness per key, not secrecy or
even unpredictability. GCM's internal encryption is CTR-mode-like: the nonce plus a
block counter generates a "keystream" that gets XORed with the plaintext. - Why nonce reuse under GCM is catastrophic: if the same key and nonce encrypt two
different messages, both use the identical keystream. XORing the two ciphertexts together
cancels the keystream out entirely, leaving the XOR of the two plaintexts, a classic
"two-time pad" break: an attacker who knows or guesses one plaintext immediately recovers
the other. GCM reuse is worse still: it can also expose the authentication subkey, letting
an attacker forge arbitrary valid messages for that key going forward.
Worked example
Say a reused keystream (from encrypting two different messages under the same key and nonce)
happens to be the bytes A5 3C 91 77. Encrypting "HELP" (48 45 4C 50 in hex) with it gives
ciphertext C1 = 48^A5, 45^3C, 4C^91, 50^77 = ED 79 DD 27. Encrypting "RUN!" (52 55 4E 21)
with the same keystream gives C2 = 52^A5, 55^3C, 4E^91, 21^77 = F7 69 DF 56. Now XOR the
two ciphertexts: C1 xor C2 = ED^F7, 79^69, DD^DF, 27^56 = 1A 10 02 71. That is exactly
"HELP" xor "RUN!" (48^52, 45^55, 4C^4E, 50^21 = 1A 10 02 71), with the keystream fully
canceled out. If an attacker already knows or can guess one plaintext ("HELP"), they recover
the other directly: M2 = M1 xor (C1 xor C2) = 48^1A, 45^10, 4C^02, 50^71 = 52 55 4E 21, which
decodes back to "RUN!". No key was ever recovered, and none was needed.
Trade-offs & pitfalls
- "Random" is a stronger property than "unique," but for GCM specifically, uniqueness is the
requirement that must never be violated; a random-but-short (96-bit) nonce chosen fresh
every time is standard practice precisely because random values are very unlikely to
collide at reasonable message volumes, not because randomness itself is the requirement. - A common real mistake is initializing a nonce counter to zero on every server restart or
every new connection, silently creating repeats across restarts or connections that share a
key.
Write a function that compares two byte strings for equality in constant time, suitable for verifying a MAC (e.g. an HMAC tag) without using a language's built-in constant-time-compare helper. Explain specifically why your implementation doesn't leak timing information, and how you'd test that claim.
Sample Answer
Approach
A naive byte-string comparison (a == b, or a loop that returns on the first mismatch) short-circuits: it stops as soon as it finds a differing byte. That means comparing a correct tag's first byte takes measurably less time than comparing a tag that's correct for the first 30 bytes and wrong on byte 31. An attacker who can measure that timing difference, even over a network with noise, can recover a valid message authentication code (MAC) one byte at a time by trying all 256 values for each position and keeping whichever one takes longest. This is exactly the kind of attack a constant-time compare exists to prevent.
The fix has two ingredients: never stop early, and never let the result of one byte's comparison affect how much work is done for the next one. Instead of comparing and branching, XOR every corresponding byte pair and OR the results together, then check that final accumulator once at the end.
def constant_time_compare(a: bytes, b: bytes) -> bool:
"""Compare two byte strings without leaking a length-prefix match via timing."""
if len(a) != len(b):
# Do a dummy pass over `a` so this branch isn't a distinguishably fast return.
# MAC length is public protocol information, not a secret, so this is defense
# in depth rather than the core of the fix.
result = 0
for byte in a:
result |= byte
return False
result = 0
for x, y in zip(a, b):
result |= x ^ y
return result == 0
Key points
x ^ yis zero only when the two bytes are equal, so OR-ing every position's XOR into one accumulator means the finalresultis zero only if every byte matched. There is no branch inside the loop whose outcome depends on secret data, so the number of operations performed is identical (a function only oflen(a)) regardless of where, or whether,aandbdiffer.- To confirm this is actually equivalent to the trusted built-in (
hmac.compare_digestin Python, or the language's equivalent), verify it agrees on both a correct tag and tags tampered at the first and last byte:
import hmac, hashlib
key, message = b"super-secret-mac-key", b"account=1042&amount=500.00"
real_tag = hmac.new(key, message, hashlib.sha256).digest()
tampered_first = bytes([real_tag[0] ^ 0xFF]) + real_tag[1:]
tampered_last = real_tag[:-1] + bytes([real_tag[-1] ^ 0xFF])
print(constant_time_compare(real_tag, real_tag)) # True
print(constant_time_compare(real_tag, tampered_first)) # False
print(constant_time_compare(real_tag, tampered_last)) # False
Running this prints True, False, False, matching a normal equality check's correctness while removing its timing signal.
Testing the timing claim
You cannot prove "no timing leak" from reading code alone; the honest way to test it is to compare relative timing behavior across many repetitions with the mismatch position deliberately varied, and confirm the naive version gets faster as the mismatch moves earlier while the constant-time version does not:
import time
def naive_compare(a, b):
if len(a) != len(b): return False
for x, y in zip(a, b):
if x != y: return False
return True
long_a = bytes([0] * 10000)
mismatch_early = bytes([1]) + bytes([0] * 9999)
mismatch_late = bytes([0] * 9999) + bytes([1])
def time_it(fn, a, b, n=2000):
start = time.perf_counter()
for _ in range(n): fn(a, b)
return time.perf_counter() - start
print("naive early/late:", time_it(naive_compare, long_a, mismatch_early), time_it(naive_compare, long_a, mismatch_late))
print("const-time early/late:", time_it(constant_time_compare, long_a, mismatch_early), time_it(constant_time_compare, long_a, mismatch_late))
On a real run this printed the naive version taking roughly three orders of magnitude longer when the mismatch was near the end than near the start, while the constant-time version's two timings were within measurement noise of each other. Exact numbers are hardware- and load-dependent, so a real audit runs many trials and looks at the statistical distribution, not a single measurement, but the qualitative signature (does timing correlate with mismatch position) is what you're checking for.
Complexity
Both the comparison and the dummy fallback pass are O(n) in the length of the inputs, with no early exit, so the constant-time version does strictly more work than a best-case naive comparison and exactly the same work as a worst-case one. Space is O(1) beyond the inputs themselves.
Edge cases
- Different-length inputs must not be rejected via an instant
return False, that branch is itself timeable; either pad to a fixed comparison length or, as shown, burn equivalent work before returning. - Compiler and interpreter optimizations can sometimes reintroduce short-circuiting (e.g. an optimizer proving a branch is dead); production code should use the language's own vetted constant-time primitive (
hmac.compare_digest,crypto/subtle.ConstantTimeComparein Go,CRYPTO_memcmpin OpenSSL) once you understand why it exists, this exercise is about understanding the mechanism, not replacing the standard tool.
Explain key derivation functions (KDFs) such as PBKDF2 and HKDF. Describe appropriate use cases for each (password stretching vs deriving multiple keys), the roles of salt and iteration/memory cost, and how to safely derive multiple cryptographic keys from a single secret.
Sample Answer
Direct answer
Both Password-Based Key Derivation Function 2 (PBKDF2) and HMAC-based Extract-and-Expand Key
Derivation Function (HKDF) are key derivation functions (KDFs), but they solve different problems:
PBKDF2 exists to slow down brute-forcing a low-entropy secret like a password, while HKDF exists
to safely stretch one already high-entropy secret into several independent keys. Using PBKDF2
where you need multiple keys, or HKDF where you need password stretching, is a common and
avoidable mistake.
Structured elaboration
- PBKDF2 (RFC 8018) repeatedly applies a pseudorandom function, usually a Hash-based Message
Authentication Code (HMAC), hundreds of
thousands of times, so that guessing a candidate password costs an attacker that same repeated
work. It is the right tool for password storage, though Argon2id is now the generally preferred
choice for new systems because it is also memory-hard (expensive in RAM, not just CPU time),
which resists Graphics Processing Unit (GPU) and Application-Specific Integrated Circuit (ASIC)
cracking rigs far better than a CPU-only iteration count does. - HKDF (RFC 5869) runs in two stages: Extract condenses a secret and a salt into a fixed-length
pseudorandom key (PRK), and Expand stretches that PRK into as many bytes of output key material
(OKM) as you need, using a distinctinfolabel per derived key. It assumes the input is already
unpredictable; it does not add work to slow down a guesser, because there is nothing to guess,
the input is presumed to already be a strong secret such as a Diffie-Hellman shared value. - Salt. In both cases, salt must be unique per secret and stored alongside the output; its job
is to stop an attacker from precomputing one table of guesses that works against every user or
every derivation at once. - Iteration and memory cost. PBKDF2's iteration count and Argon2's memory/time parameters are
the slowing-down knob; HKDF has no such knob at all, deriving multiple keys from one PRK is
meant to be fast.
Worked example
Every value below comes from actually running the code, not from memory of the standard:
import hashlib, hmac
dk = hashlib.pbkdf2_hmac("sha256", b"correct horse battery staple",
b"a-16-byte-salt!!", 600_000, dklen=32)
print("PBKDF2-HMAC-SHA256, 600k iterations:", dk.hex())
def hkdf_extract(salt, ikm):
return hmac.new(salt, ikm, hashlib.sha256).digest()
def hkdf_expand(prk, info, length):
t, okm, counter = b"", b"", 1
while len(okm) < length:
t = hmac.new(prk, t + info + bytes([counter]), hashlib.sha256).digest()
okm += t
counter += 1
return okm[:length]
master = bytes(32) # a placeholder high-entropy secret, e.g. an ECDH shared value
prk = hkdf_extract(b"", master)
enc_key = hkdf_expand(prk, b"app1 enc-key v1", 32)
mac_key = hkdf_expand(prk, b"app1 mac-key v1", 32)
print("enc_key:", enc_key.hex())
print("mac_key:", mac_key.hex())
print("keys differ:", enc_key != mac_key)
PBKDF2-HMAC-SHA256, 600k iterations: eee4f7bf2738c37a2307ccc294c505a9665310ddc03ee33f34cfb86919b8f63b
enc_key: 79b0012d2c0c2c236622a523aa59827fe08788f4475c983884c1b1ec523b9978
mac_key: b188ea23f17faf8ea8435b9caff54595d9c4a746f0f2571d97c9225c739c5ab7
keys differ: True
Note the shape of the derivation: one Extract call, then two Expand calls with different info
strings, produces two independent 32-byte keys from a single master secret, an encryption key and
a MAC key, without ever reusing the same bytes for both purposes.
Trade-offs & pitfalls
- Common wrong turn: running HKDF directly on a password. A password is low-entropy, so HKDF's
fast Extract/Expand steps do nothing to slow an offline guesser down; pre-process it through a
slow KDF (Argon2id or PBKDF2) first if a password is ever the input. - Common wrong turn: reusing one derived key for two purposes (say, both encryption and
authentication) instead of deriving two labeled keys as shown above. Domain separation via
distinctinfostrings is cheap and removes an entire class of cross-purpose key-reuse bugs. - Recommendation: Argon2id (or PBKDF2 with a high iteration count, if constrained to it) for
password storage; HKDF with explicit, uniqueinfolabels and a fresh, random salt per context
for deriving multiple keys from one high-entropy secret.
Explain the core security properties a cryptographic hash function must have (preimage resistance, second-preimage resistance, collision resistance), name a couple of common algorithms, and give one example each of where a hash is the right tool (integrity checks, content-addressing) and where it is not (storing passwords without salting and stretching).
Sample Answer
Direct answer
A cryptographic hash function must be preimage resistant (given an output, you cannot find
an input that produces it), second-preimage resistant (given one input, you cannot find a
different input with the same output), and collision resistant (you cannot find any two
distinct inputs that share an output at all). Common algorithms today are SHA-256 and SHA-3;
MD5 and SHA-1 are broken for collision resistance and should not be used where that property
matters.
Structured elaboration
- Preimage resistance: given
H(m) = h, it should be computationally infeasible to find
anymthat producesh. This is what makes a hash "one-way." - Second-preimage resistance: given a specific
m1, it should be infeasible to find a
differentm2withH(m1) = H(m2). - Collision resistance: it should be infeasible to find any pair
m1 != m2with
H(m1) = H(m2), without fixing either input in advance. This is the property MD5 and SHA-1
have both practically broken (real collision attacks have been demonstrated for both). - Where a hash is the right tool: integrity checks (comparing a downloaded file's hash
against a published one to detect corruption or tampering), content-addressing (Git commit
hashes, package registries keying content by its digest so identical content always maps to
the same address), and as the digest step inside a digital signature: signing algorithms
sign a fixed-size hash of a message rather than the message itself, since asymmetric
operations are expensive on large inputs. - Where it is not the right tool: storing passwords with a bare, unsalted hash. Hash
functions are deliberately fast, which is exactly wrong for password storage: an attacker
with a stolen hash dump can try billions of guesses per second on commodity GPUs. Password
storage needs a slow, memory-hard key derivation function (Argon2id, scrypt, bcrypt), not a
general-purpose hash used directly.
Worked example
To see why collision resistance is the strongest property, compare a real hash to a toy,
clearly-broken one: H(x) = x mod 97. Take m1 = 5 and m2 = 102. 102 mod 97 = 5, so
H(5) = H(102) = 5: a collision found by inspection, with no search at all. That is exactly
what "not collision resistant" looks like. A real hash like SHA-256 produces a 256-bit output,
so the best known way to find any colliding pair is a generic birthday-bound search of roughly
2^128 attempts (the square root of 2^256 possible outputs), which is computationally out
of reach with current or foreseeable hardware. The mod-97 toy fails instantly because its
output space is only 97 values; a cryptographic hash needs both a large output space and no
structural shortcut into it.
Trade-offs & pitfalls
- Collision resistance and preimage resistance are different properties; a function can lose
one without immediately losing the other, which is why "MD5 has collisions" does not
automatically mean "MD5 leaks passwords," but it does mean you should not trust MD5 for
anything where an attacker choosing two colliding inputs would matter (like forging a signed
document). - "Hashing" and "encryption" are often confused: hashing is one-way and not meant to be
reversed at all, encryption is two-way and meant to be reversed with the right key. A hash
cannot be "decrypted" back to the original input, by design.
In Python 3 using the 'cryptography' library, you find code that encrypts data using AES in ECB mode. Rewrite the encryption and decryption flow to use AES-GCM properly, showing secure key generation, nonce selection, encryption with associated data, and authentication tag verification. Explain how you persist nonce and tag alongside ciphertext.
Sample Answer
Approach
Electronic Codebook (ECB) mode encrypts every block of plaintext independently with the same key, so identical plaintext blocks always produce identical ciphertext blocks. That leaks structure (the classic demonstration is encrypting an image in ECB and still being able to make out its shapes in the ciphertext), and it has no built-in integrity check at all. The fix is to move to Galois/Counter Mode (GCM), which encrypts with a per-message nonce so identical plaintext blocks no longer produce identical ciphertext, and produces an authentication tag so any tampering is detected on decryption rather than silently accepted.
import os
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
def generate_key() -> bytes:
# 256-bit key from the operating system's cryptographically secure random source.
# This assumes the key itself is already proper key material (e.g. from a key-management
# service or a password-based key derivation function), not derived carelessly here.
return AESGCM.generate_key(bit_length=256)
def encrypt(key: bytes, plaintext: bytes, associated_data: bytes = b"") -> bytes:
"""Encrypt with AES-GCM. Returns nonce || ciphertext || tag as one storable blob."""
aesgcm = AESGCM(key)
nonce = os.urandom(12) # 96-bit random nonce: never reuse this value under the same key
ct_and_tag = aesgcm.encrypt(nonce, plaintext, associated_data) # tag is appended automatically
return nonce + ct_and_tag
def decrypt(key: bytes, blob: bytes, associated_data: bytes = b"") -> bytes:
"""Split the stored blob back into nonce and ciphertext+tag, then verify-and-decrypt."""
aesgcm = AESGCM(key)
nonce, ct_and_tag = blob[:12], blob[12:]
return aesgcm.decrypt(nonce, ct_and_tag, associated_data) # raises on any tampering
key = generate_key()
plaintext = b"ssn=123-45-6789;plan=gold"
aad = b"record-id:8842" # authenticated but not encrypted, e.g. a routing or record id
blob = encrypt(key, plaintext, aad)
print("stored blob length:", len(blob), "=", 12, "(nonce) +", len(plaintext), "(plaintext) + 16 (tag)")
print("decrypted matches original:", decrypt(key, blob, aad) == plaintext)
tampered = bytearray(blob)
tampered[20] ^= 0x01
try:
decrypt(key, bytes(tampered), aad)
except Exception as e:
print("tamper detected:", type(e).__name__)
Running this prints the blob length breakdown, decrypted matches original: True, and tamper detected: InvalidTag, a one-bit flip in the stored ciphertext is caught rather than silently decrypted into garbage.
Key points
- The nonce is generated fresh per call with
os.urandom(12)and stored alongside the ciphertext (prepended here), never hardcoded and never derived from predictable state like a record counter that could repeat. - Associated data (
aad) is authenticated but not encrypted, useful for binding context (a record ID, a protocol version byte) to the ciphertext so it cannot be silently swapped onto a different record; tampering withaadalone also fails the tag check. - The library raises on tamper rather than returning corrupted plaintext, callers must not catch that exception and fall back to treating the data as valid.
Complexity
Both encryption and decryption are O(n) in the plaintext length: one pass through the data for the counter-mode cipher and the authentication tag computation, done together in the same pass. Space overhead beyond the plaintext is fixed and small: 12 bytes of nonce plus 16 bytes of tag per message, regardless of message size.
Edge cases
- Never reuse a nonce under the same key; with a 96-bit random nonce, rotate the key well before the number of messages approaches the birthday-bound risk region rather than relying on randomness alone at very high volume.
- If
associated_datais empty, passNoneorb""consistently between encryption and decryption, a mismatch there fails the tag check even though the ciphertext itself is untouched. - Persist the nonce and tag together with the ciphertext; losing either makes the data unrecoverable, since Galois/Counter Mode has no way to decrypt without them.
Unlock Full Question Bank
Get access to all 37 Cryptography Fundamentals interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.