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.
Explain how authenticated key exchange (AKE) protocols combine confidentiality and authentication. Choose a specific AKE (e.g., TLS 1.3 handshake with ECDHE + signatures) and describe how it defends against man-in-the-middle attacks and provides assurance on peer identity.
Sample Answer
Direct answer
Authenticated key exchange (AKE) combines two things that, done separately, would each be insecure on their own: a key-exchange step (typically Diffie-Hellman) that produces a shared secret neither party had before, and an authentication step that proves who you're actually exchanging that secret with. Without authentication, an unauthenticated Diffie-Hellman exchange is trivially defeated by a man-in-the-middle (MITM) attacker who performs the exchange separately with each side and relays traffic between two secrets it controls, both parties end up with a working shared secret, just not with each other.
How Transport Layer Security (TLS) 1.3's handshake does this
TLS 1.3's default handshake is an authenticated key exchange built from Elliptic-Curve Diffie-Hellman Ephemeral (ECDHE) key exchange plus digital signatures:
- The client sends a fresh, ephemeral elliptic-curve key share. The server responds with its own fresh ephemeral key share; combining them (each side using its own private half and the other's public half) gives both sides the same shared secret, without either share ever having existed before this one connection.
- The server also sends its certificate and a signature, computed with the private key matching that certificate, over the handshake transcript so far. The client verifies the signature against the certificate's public key and validates the certificate chain up to a trusted root, this is the authentication step.
- Because the signature commits to the specific ephemeral key share exchanged in this handshake, an attacker sitting in the middle cannot substitute their own key share without invalidating the signature, they don't hold the private key needed to produce a valid one for the real server's certificate.
Why this defeats a man-in-the-middle attacker
An attacker relaying an unauthenticated exchange succeeds because neither side can tell they're talking to the attacker instead of each other. Binding the key exchange to a signature the attacker cannot forge closes that gap: the attacker can still see the ephemeral public values (they're sent in the clear), but cannot produce a valid signature over a handshake transcript containing their own substituted values, so the client detects the tampering and aborts rather than completing a handshake with an unauthenticated middle party.
Worked example (why ephemeral keys matter here too)
Using fresh ephemeral key shares per connection, rather than reusing a long-term Diffie-Hellman key, is what gives TLS 1.3 forward secrecy: even if the server's long-term signing key is later compromised, an attacker who recorded past encrypted traffic still cannot recover the ephemeral per-session secrets, since those were never derived from, or transmitted alongside, the long-term key at all, they existed only for the duration of that one handshake and were discarded afterward.
Trade-offs and pitfalls
Authentication only defends against a man-in-the-middle attacker if certificate validation is actually performed correctly (checking the chain to a trusted root, not just that "a" signature is present) and the client's trust store hasn't itself been tampered with, an attacker who can inject a rogue trusted root defeats the entire scheme regardless of how sound the key-exchange math is. This is why authenticated key exchange is properly understood as two dependent guarantees, not two independent ones: the key exchange is only as trustworthy as the authentication binding it to a specific, verified identity.
Design a certificate revocation-checking approach for a global-scale service: compare CRLs, OCSP, and OCSP stapling on latency, availability, and privacy, and explain when short-lived certificates are a better alternative to revocation checking altogether. How would you detect and respond to a spike in failed revocation checks across your client fleet?
Sample Answer
Framing
The job is to let a client learn, in near real time and at global scale, whether a certificate it just received is still trustworthy, without that check itself becoming a single point of failure or a privacy leak. The three classic options, a Certificate Revocation List (CRL), the Online Certificate Status Protocol (OCSP), and OCSP stapling, sit on a spectrum from "cheap and stale" to "fresh but fragile," and short-lived certificates are a way to sidestep the whole problem rather than solve it better.
Comparing the options
| Approach | Latency | Availability | Privacy |
|---|---|---|---|
| CRL (a signed, periodically-published list of revoked certificate serial numbers) | No per-connection network call, but lists can be large and only as fresh as the last publish (often hours to a day old) | Very robust: clients can cache the list and keep working if the certificate authority (CA) is briefly unreachable | Good: no query reveals which specific site you're visiting |
| OCSP (a live, per-certificate revocation query to the CA) | Fresher (minutes), but adds a real-time network round trip to the CA on every new connection | Weak on its own: if the CA's OCSP responder is slow or down, clients either block (hurts availability) or "soft-fail" and skip the check (hurts security) | Poor: the CA sees which certificate, and therefore which site, each client is checking |
| OCSP stapling (the server itself fetches a signed OCSP response and attaches it to the handshake) | Best of both: no extra client round trip and fresh within the response's validity window | Good: the server, not each client, depends on the CA being reachable | Good: the CA never learns which clients are visiting which site, since the server does the fetching, not each browser |
When short-lived certificates beat revocation checking
If a certificate's validity window is a few days instead of a year (a pattern popularized by modern automated issuance), a compromised key becomes far less useful on its own: it expires before most CRL/OCSP infrastructure would even have propagated a revocation. This trades an ongoing revocation-checking system for an operational one, reliable, frequent automated reissuance, and it removes the OCSP privacy leak and the CRL freshness problem entirely, at the cost of needing issuance automation that cannot be allowed to fail silently.
Detecting and responding to a spike in failed revocation checks
- Detection: alert on the rate of OCSP failures or stapled-response absences per fleet, per certificate authority, and per region, since a global spike usually means an infrastructure problem (CA outage, network partition to the CA) while a narrow spike on one certificate points at that certificate specifically (possibly a real revocation event or an expired/misconfigured staple).
- Response: because a bad response here fails toward either "block legitimate traffic" or "silently accept a possibly-revoked certificate," decide and document the fallback behavior in advance (most production systems soft-fail with heavy monitoring rather than hard-fail, accepting the residual risk in exchange for availability) and treat a sustained spike as an incident that pages someone, not a metric that sits in a dashboard, because both failure directions have real security or availability consequences.
Trade-offs and pitfalls
OCSP stapling only helps if the server actually refreshes and serves a valid staple, a server that silently falls back to an unstapled response quietly reintroduces the privacy and latency costs of plain OCSP. Short-lived certificates only remove the revocation problem if issuance automation is treated as production infrastructure with its own on-call ownership, a failed renewal a few hours before expiry is now an outage, not a delayed patch.
Implement PKCS#7 padding and unpadding functions in Python for a block cipher with a given block size. Provide: def pad(data: bytes, block_size: int) -> bytes and def unpad(data: bytes, block_size: int) -> bytes. The unpad function must validate padding and raise an exception for invalid padding, and you should explain how to validate padding without creating an easy padding oracle vulnerability during decryption flows.
Sample Answer
Direct answer
PKCS#7 padding (defined in RFC 2315, and reused unchanged in modern standards for block ciphers)
fills the last block of a message so its length becomes a multiple of the cipher's block size: the
value of every padding byte equals the count of padding bytes added, from 1 up to the block
size. Unpadding must check that consistently and reject anything else, but it must do that check
without leaking, through timing, which specific byte was wrong, since that leak is exactly what a
padding oracle attack exploits.
Structured elaboration
- Approach.
padcomputes how many bytes are missing to reach a multiple ofblock_size
(always between 1 andblock_size, even when the input is already a multiple, since padding
must always be present sounpadcan find it) and appends that many bytes, each holding that
count as its value. - Approach.
unpadfirst checks the length is a nonzero multiple ofblock_size, reads the
last byte as the claimed padding count, and rejects it outright if it is 0 or bigger than
block_size. Only then does it verify every one of the claimed padding bytes actually holds
that value. - Avoiding a padding oracle. The verification loop below never returns as soon as it finds a
mismatch; it OR's every byte's difference into an accumulator and checks it once at the end, so
the number of comparisons performed does not depend on where the first bad byte was. That
alone does not make the surrounding system safe: the real defense is to authenticate the
ciphertext (via an AEAD cipher, authenticated encryption with associated data, or a Message
Authentication Code, MAC, such as HMAC, computed over the ciphertext) before this function
is ever called during decryption, so a tampered ciphertext is rejected before its padding is
inspected at all.
Worked example
class PaddingError(ValueError):
pass
def pad(data: bytes, block_size: int) -> bytes:
if not (1 <= block_size <= 255):
raise ValueError("block_size must be between 1 and 255")
pad_len = block_size - (len(data) % block_size)
return data + bytes([pad_len]) * pad_len
def unpad(data: bytes, block_size: int) -> bytes:
if not data or len(data) % block_size != 0:
raise PaddingError("invalid padding length")
pad_len = data[-1]
if pad_len < 1 or pad_len > block_size:
raise PaddingError("invalid padding value")
# Constant-time check: touch every candidate padding byte instead of
# returning on the first mismatch, so timing does not reveal *which*
# byte was wrong.
diff = 0
for b in data[-pad_len:]:
diff |= b ^ pad_len
if diff != 0:
raise PaddingError("invalid padding bytes")
return data[:-pad_len]
block_size = 16
msg = b"attack at dawn!!" # 16 bytes, exactly one block
padded_short = pad(b"hi", block_size)
padded_exact = pad(msg, block_size)
print("pad(b'hi', 16) =", padded_short, "len:", len(padded_short))
print("pad(16-byte msg, 16) =", padded_exact, "len:", len(padded_exact))
print("unpad round-trips 'hi' :", unpad(padded_short, block_size) == b"hi")
print("unpad round-trips full :", unpad(padded_exact, block_size) == msg)
tampered = bytearray(padded_short)
tampered[-1] ^= 0xFF
try:
unpad(bytes(tampered), block_size)
print("tampered padding accepted (BUG)")
except PaddingError as e:
print("tampered padding rejected:", e)
Output (deterministic, this exact run reproduces it):
pad(b'hi', 16) = b'hi\x0e\x0e\x0e\x0e\x0e\x0e\x0e\x0e\x0e\x0e\x0e\x0e\x0e\x0e' len: 16
pad(16-byte msg, 16) = b'attack at dawn!!\x10\x10\x10\x10\x10\x10\x10\x10\x10\x10\x10\x10\x10\x10\x10\x10' len: 32
unpad round-trips 'hi' : True
unpad round-trips full : True
tampered padding rejected: invalid padding value
Trade-offs & pitfalls
- Complexity: both functions are O(n) in the input length; the constant-time scan adds no
asymptotic cost since it is bounded byblock_size(at most 255 byte comparisons). - Edge cases: an already-block-aligned input still gets a full extra block of padding (a common
point of confusion, PKCS#7 never leaves zero padding bytes); an empty ciphertext; apad_lenof
0 or greater thanblock_size, both invalid and must be rejected before the byte-by-byte check
runs; a ciphertext whose length is not a multiple ofblock_sizeat all, which is a format error
distinct from a padding error but should still surface a single generic exception. - A constant-time comparison inside
unpadreduces one class of timing leak, but if this function
is called on attacker-controlled ciphertext before a MAC or AEAD tag has been checked, the
system is still exploitable: the attacker does not need a timing side-channel if the application
simply returns a different HTTP status or error string for "bad padding" versus "bad MAC".
Encrypt-then-MAC (or AEAD outright) removes the padding oracle at the protocol level; this
function alone only removes it at the instruction level.
State recommended key length guidance for common algorithms: AES (symmetric), RSA (classical public-key), and elliptic curve algorithms (ECDSA/ECDH). Explain why key length matters and what operational considerations (performance, lifespan, algorithm migration) influence your choice of length.
Sample Answer
Direct answer
Roughly: AES-128 or AES-256 for symmetric keys, at least RSA-2048 with RSA-3072 preferred for
longer-lived data, and a 256-bit elliptic curve (like P-256) for ECDSA/ECDH. These are not
interchangeable "bit strengths": because the underlying hard problems differ, RSA needs a
much larger key than AES or ECC to reach the same practical security level.
Structured elaboration
Key length matters because it determines how expensive the best known attack is. For a
symmetric cipher, the best general attack is brute force over the key space, so security
scales directly and exponentially with key bits. RSA's security instead rests on integer
factorization, which has sub-exponential algorithms (the General Number Field Sieve), so RSA
needs a much larger key to match a given symmetric strength. Elliptic-curve cryptography
relies on the discrete logarithm problem over an elliptic curve, which has no known
sub-exponential attack, so it reaches strong security with much smaller keys than RSA.
Roughly matched security levels (NIST SP 800-57 style guidance):
| Symmetric-equivalent strength | AES | RSA | ECC (ECDSA/ECDH) |
|---|---|---|---|
| ~128-bit | AES-128 | RSA-3072 | P-256 |
| ~192-bit | AES-192 | RSA-7680 | P-384 |
| ~256-bit | AES-256 | RSA-15360 | P-521 |
Operational considerations that influence the choice:
- Performance: RSA key generation and private-key operations get noticeably slower as key
size grows; ECC stays comparatively cheap even at higher security levels, which is why TLS
handshakes favor ECDHE over large-RSA key exchange today. - Lifespan: a key protecting data that must stay confidential for decades (a root CA, an
archival encryption key) should sit at a higher security margin than a short-lived TLS
session key, since attacker capability only improves over time. - Algorithm migration headroom: teams often deliberately keep some headroom above the
current minimum recommendation, so that a future algorithm migration (moving to a larger
key size, or off an algorithm entirely) can happen on a planned schedule rather than as an
emergency re-key after a break is announced.
Worked example
A document-signing service needs signatures that remain verifiable for 20-year regulatory
retention. A TLS session key, by contrast, only needs to resist attack for the minutes the
connection is open. Both could technically use "128-bit class" security today, but the
signing service deliberately picks RSA-3072 over RSA-2048 (or a 384-bit curve over a 256-bit
one) precisely because of the lifespan consideration: a 20-year window gives attacker capability
two decades to improve, so the team spends a bit more compute per signature now to buy margin
that a short-lived session key does not need.
Trade-offs & pitfalls
- RSA-2048 is still widely deployed and considered acceptable for most near-term use, but
guidance is trending toward RSA-3072 for anything expected to remain secure for many years;
treat any bare "RSA-2048 is fine forever" claim with suspicion. - Bumping AES from 128 to 256 bits has essentially no practical performance cost on modern
hardware (AES-NI accelerates both equally), so the "just use AES-256 to be safe" instinct is
cheap here in a way it is not for RSA.
Why can't you build a secure MAC by simply computing hash(key || message)? Walk through the HMAC construction (the nested inner/outer padding), and explain specifically what attack this defends against that the naive approach doesn't.
Sample Answer
Direct answer
hash(key || message) is forgeable because of length-extension: with a Merkle-Damgard hash
function (MD5, SHA-1, plain SHA-256), the hash's output is its complete internal state after
processing the input, so an attacker who sees that output can resume hashing from it and
compute a valid hash for key || message || extra, appending attacker-chosen data, without
ever learning the key. HMAC defeats this with a nested double-hash construction where the
outer hash's input is prefixed with a value derived from the key, so an attacker extending the
inner hash's output has no way to continue the outer hash without knowing the key.
Structured elaboration
- Why the naive construction breaks: a Merkle-Damgard hash processes input in fixed-size
blocks, updating an internal state block by block, and the final output is simply that
internal state after the last block plus padding. GivenH(key || message)and the length
ofkey || message, an attacker knows exactly what padding was applied and can treat the
published hash as the internal state at that point, then keep hashing forward with any
additional blocks they choose. The result is a validH(key || message || padding || extension)for an attacker-chosen extension, with the key never touched at any point. - HMAC's nested construction:
HMAC(K, m) = H( (K' xor opad) || H( (K' xor ipad) || m ) ),
whereK'is the key padded (or, if too long, first hashed) to the hash's block size,ipad
is the byte0x36repeated to block length, andopadis the byte0x5crepeated to block
length. The message is hashed once with a key-derived prefix (the inner hash), and that
entire result is hashed again with a different key-derived prefix (the outer hash). - Why this defeats length extension: length extension lets an attacker continue a hash
computation from a known output, but it does not let them start a new hash computation
whose first block they don't know. The outer hash's input begins withK' xor opad, a value
that depends on the secret key; an attacker who performs length extension on the inner
hash's output still cannot reconstruct or extend the outer hash, because they never had
K' xor opadto begin with. The double nesting, not just prepending the key once, is what
closes the gap.
Worked example
A simplified toy illustrates the core idea without needing a real hash implementation. Say a
toy "hash" processes one block at a time by adding it into a running state modulo 256, and
the final state is the output (this mirrors, in miniature, how a Merkle-Damgard hash's output
is its last internal state). Let the secret key be block value 200 and the message be two
blocks, 10 and 5. Processing key || message: state starts at 0, then
0 + 200 = 200, then 200 + 10 = 210, then 210 + 5 = 215. The published "hash" is 215.
An attacker who never learned the key 200 can still continue from the published state: to
append an extension block of 50, they compute 215 + 50 = 265, and 265 mod 256 = 9. That
9 is exactly what hashing key || message || 50 would have produced, computed without ever
knowing 200. Real Merkle-Damgard hashes add a padding block in between that the attacker
must account for using the known message length, but the vulnerability is the same one this
toy exposes: the output does not hide the internal state, it is the internal state, so
anyone who sees it can keep going.
Trade-offs & pitfalls
- A common near-miss is
hash(message || key)(key at the end) instead of at the start; this
avoids classic length-extension but has its own weaknesses and is still not equivalent to
HMAC's proven construction, so it is not a safe substitute. - HMAC's security can be reduced to weaker, more provable assumptions about the underlying
compression function than "the hash behaves like a random oracle," which is part of why it
is the standard rather than an ad hoc double-hash of your own design. - SHA-3, unlike MD5/SHA-1/SHA-2, is not built on the Merkle-Damgard structure and is not
vulnerable to this specific length-extension attack even in the naivehash(key || message)form, though HMAC (or SHA-3's own keyed mode) is still the standard, well-analyzed
choice rather than relying on that property alone.
Unlock Full Question Bank
Get access to all Cryptography Fundamentals interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.