Skip to content
Tech Interview Prep
Technical interview guide

Encryption Fundamentals

Symmetric vs. asymmetric encryption, hashing, and how TLS combines them.

Minutes to read
4
Practice MCQs
25
Interview Q&A
25
Edition
v4
Editorial status
Reviewed

Scope: FIPS 197 update 1, NIST SP 800-57 Part 1 Rev. 5, RFC 8446, and official OWASP guidance accessed 2026-08-31..

Interview Q&A

Treat each question like a live interview question: answer out loud first (structure, assumptions, tradeoffs), then open the model answer to spot gaps and rehearse a tighter follow-up.

Curated: · Written: · Reviewed:

25 questions

Q&A-1

Compare encryption, hashing, MACs, and digital signatures.

Answer

Four primitives, four different questions. Encryption answers "can an eavesdropper read this?" Hashing answers "has this changed?" A MAC answers "did someone holding our shared key produce this?" A signature answers "can a third party verify who produced this without trusting the verifier?"

Assumptions: you are choosing primitives for a protocol, not a product; both ends are under your control or you have a PKI; and you are on current mainstream versions.

primitivepropertykey materialwho can produce a valid valueconcrete instance
AEAD encryptionconfidentiality + integritysymmetric, sharedany key holderAES-256-GCM, 128-bit tag, 96-bit nonce
hashpreimage + collision resistancenoneanyoneSHA-256, 256-bit digest
MACintegrity + authenticity among holderssymmetric, sharedany key holderHMAC-SHA-256, key ≥ 256 bits
signatureintegrity + authenticity + third-party verifiabilityprivate/public paironly the private-key holderEd25519, 64-byte signature, 32-byte public key

Why each behaves as it does. A hash is unkeyed, so anyone can recompute it: replacing a file and its digest together is trivial, which is why a bare SHA-256 checksum does not authenticate an attacker-controlled download. SHA-256 is Merkle–Damgård, so the naive construction H(secret ‖ message) is vulnerable to length extension; HMAC exists to close that. HMAC-SHA-256 with a 256-bit key gives roughly 256-bit forgery resistance, but every holder of the key can forge, so it cannot settle a dispute with an outsider. Ed25519 gives ~128-bit security with 64-byte signatures and deterministic signing, which removes the ECDSA nonce-reuse failure mode that leaked private keys on the PS3 and in some Android Bitcoin wallets. RSA-2048 gives ~112-bit security and 256-byte signatures; verification is cheap (tens of microseconds) and signing is expensive (~1 ms), the opposite balance from Ed25519.

Failure modes worth naming. Reusing an AES-GCM nonce under the same key leaks the authentication subkey and XORs the two plaintexts: enforce a counter-based nonce that survives restarts. AES-CBC without a MAC is malleable and has produced padding oracles (Lucky13, POODLE). HMAC keys shorter than the hash output length weaken the function (RFC 2104). SHA-1 and MD5 are broken for collision resistance: SHAttered produced a SHA-1 collision in 2017, and MD5 collisions take seconds. A valid Ed25519 signature proves possession of a private key, not who owns it; without a certificate chain or a pinned key, it authenticates nothing.

What changes the choice: non-repudiation to a third party forces a signature; a shared key with only tamper detection needed favors HMAC (cheaper, no PKI); confidentiality forces an AEAD, never raw CBC or CTR; comparing a secret against a stored value calls for a password hash (Argon2id), not SHA-256.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-2

Why do production systems combine symmetric and asymmetric cryptography?

Answer

The short answer. Asymmetric crypto does the one thing symmetric crypto can't: let two parties who have never met agree on a secret and prove who they are. Symmetric crypto does the one thing asymmetric can't: protect bulk data at line rate. So production protocols spend asymmetric operations once per connection (authenticate, agree a key) then switch to symmetric AEAD for every byte after that. The protocol, not an ad-hoc mix of primitives, is the unit of correctness.

Assumptions I'd state up front. TLS 1.3, ephemeral ECDHE (X25519), AEAD records (AES-GCM or ChaCha20-Poly1305), X.509 certificates validated against a trust store. If you already share a key out of band (WireGuard, TLS-PSK, a service mesh issuing SPIFFE identities) you can drop the asymmetric half entirely. That's a legitimate design, not a downgrade.

Mechanism, as a trace.

  1. Client sends ClientHello with a fresh X25519 key share and a cipher list.
  2. Server replies with its key share, then a Certificate, then a CertificateVerify: a signature over the transcript hash, made with the certificate's private key.
  3. Both sides run HKDF-Extract/Expand over the ECDHE shared secret to derive handshake secrets. The signature binds the ephemeral key to the certificate identity; the transcript hash binds the whole exchange, so a spliced handshake fails the Finished check.
  4. Application traffic keys are derived from that secret. Every record is then AES-GCM or ChaCha20-Poly1305.

Why the split, in numbers. Order-of-magnitude on a modern x86-64 core with AES-NI: one RSA-2048 private-key operation costs about a millisecond; X25519 agreement is tens of microseconds; AES-GCM runs at multiple GB/s. You cannot afford an asymmetric operation per record, and you cannot get authentication from a shared secret alone. Measure your own hardware: these are ballpark.

OperationRough costFrequency
X25519 key agreementtens of µsonce per handshake
RSA-2048 sign~1 msonce per handshake
AES-128-GCMGB/severy record

Failure modes, with detection and cost.

  • Nonce reuse in GCM. Two records under the same key and nonce let an attacker recover the GHASH authentication key and forge. You cannot detect it after the fact: you prevent it by counting records per key and rekeying before the limit (NIST SP 800-38D caps random 96-bit nonces at 2^32 invocations per key). Cost: forced rekey, session resets, and treating everything under that key as compromised.
  • Certificate validation skipped or misconfigured: hostname not checked, a corporate root trusted too broadly. Detection: pinning violations, certificate-transparency monitoring, unexpected issuers. Cost: full credential rotation and an incident review.
  • Entropy failure at boot. VMs cloned from a snapshot can share ephemeral keys. Detection: compare public key shares across the fleet for duplicates. Cost: rebuild images, rotate. The Debian OpenSSL bug (CVE-2008-0166) is the canonical version of this.
  • Downgrade to TLS 1.2 with RSA key exchange. You lose forward secrecy silently. Detection: alert on any negotiated version or cipher below your floor. Cost: client upgrades and policy enforcement.
  • Session-ticket keys never rotated. Resumed sessions lose forward secrecy. Detection: track ticket-key age. Cost: rotate and invalidate outstanding tickets.

When not to use it. Inside a single trust domain with a pre-shared key, the asymmetric half buys you nothing but latency. And never hand-roll the combination: transcript binding, downgrade resistance, key derivation and error handling are where the bugs live, and a protocol that already got them right is cheaper than one you write.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-25

Where does the randomness behind your service's keys, IVs and salts actually come from, and what happens when that source is weak or duplicated?

Answer

The 90-second answer. Every key, IV, nonce and salt comes from the OS CSPRNG (getrandom(2) on Linux, BCryptGenRandom on Windows, SecRandomCopyBytes on Apple) or, better, from a KMS/HSM that generates the key inside its own validated DRBG so the raw bytes never exist in my process. A general-purpose PRNG is not acceptable because it is built for reproducibility, not unpredictability: Python's random is Mersenne Twister and is fully reconstructible from 624 consecutive 32-bit outputs, Java's java.util.Random is a 48-bit LCG, Go's math/rand is deterministic unless explicitly seeded. None are backtracking-resistant, and seeding one from the clock or PID collapses the keyspace to something enumerable.

python

wrong: Mersenne Twister, state recoverable from output

import random key = bytes(random.getrandbits(8) for _ in range(32))

right: os.urandom -> getrandom(2), blocks until the CRNG is seeded

import secrets key = secrets.token_bytes(32) salt = secrets.token_bytes(16) # unique per password

Go is crypto/rand.Read, Java is java.security.SecureRandom. getrandom() is preferred over reading /dev/urandom directly because it blocks until the kernel CRNG is initialised (since Linux 5.6 /dev/urandom does too, but the syscall makes the contract explicit and lets you pass GRND_NONBLOCK to fail closed instead of silently returning weak bytes at early boot).

In practice I don't generate data keys in the application at all. I call KMS GenerateDataKey/GenerateRandom; the HSM's DRBG is FIPS 140-3 validated and SP 800-90A-compliant, and the key comes back wrapped. HKDF (RFC 5869) is for deriving subkeys from an already high-entropy secret: it cannot add entropy, so weak input keying material yields weak output.

Where it goes wrong.

FailureMechanismBlast radius
fork() without atfork handlingchild inherits the parent DRBG state; both emit the same streamevery key and token issued by either process until reseed
VM clone or snapshot restorecloned guest resumes an identical CRNG stateduplicate keys across hosts you believed independent; cross-tenant key collision
Container image or AMI with a baked seedsame seed on every bootfleet-wide identical keys
Embedded device with no entropy at bootDRBG seeded from an uninitialised pool or a constantpredictable keys, offline brute force
Debian OpenSSL, 2006–2008entropy sources removed by patch; effective keyspace ~2^15every key generated on affected hosts is enumerable

A 32-bit-seeded PRNG gives 2^32 ≈ 4.3×10^9 candidate keys. At 10^9 AES-256 key trials per second, one GPU, that is roughly four seconds to recover the key. A 256-bit CSPRNG output is not enumerable at any scale.

Detecting it. Fail closed at startup: call getrandom(GRND_NONBLOCK) and refuse to boot on EAGAIN rather than generate. Keep a key-check-value registry, a truncated SHA-256 or AES-KCV of every key generated, and alert on a collision between hosts that should be independent. Scan signature corpora for repeated ECDSA r values; the 2013 Android SecureRandom bug let anyone recover private keys from duplicated nonces. If you own an entropy source, run the SP 800-90B continuous health tests (repetition count, adaptive proportion). Add a CI test that forks, generates in both processes, and asserts the outputs differ.

Remediation. Assume everything generated in the window is compromised: rotate the keys, revoke and re-issue tokens and sessions, re-sign artifacts, and force password resets where salts collided. Duplicated salts don't break the hash, but one rainbow table then covers every affected account. Then remove the source: move generation into the KMS, add the startup fail-closed check, and keep the collision detector so the next occurrence surfaces in minutes rather than in a post-incident review.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-12

How does Authenticated Encryption with Associated Data (AEAD) work, and why does combining independent encryption and MAC constructions often introduce vulnerabilities?

Answer

An Authenticated Encryption with Associated Data (AEAD) scheme simultaneously guarantees confidentiality, integrity, and authenticity for a plaintext message, while binding cleartext metadata, the Additional Authenticated Data (AAD), to the ciphertext. AAD is authenticated but not encrypted, which prevents tampering with routing headers, protocol versions, or tenant IDs.

Core Mechanics (e.g., AES-GCM)

Under NIST SP 800-38D, AES-GCM operates over a symmetric key $K$, a nonce/IV $N$, plaintext $P$, and associated data $A$:

  1. Confidentiality: Uses counter mode (CTR). AES encrypts incrementing counter blocks derived from $N$ to generate a keystream, which is XORed with $P$ to produce ciphertext $C$.
  2. Authentication: Derives a subkey $H = \text{AES}_K(0^{128})$. $A$ and $C$ are zero-padded to 128-bit block boundaries, concatenated with their bit-lengths, and evaluated as a polynomial over the Galois field $\text{GF}(2^{128})$ via GHASH.
  3. Tag Generation: The GHASH output is masked with an encrypted initial counter block: $T = \text{GHASH}_H(A, C) \oplus \text{AES}_K(J_0)$.
  4. Decryption and Verification: The receiver evaluates the candidate tag $T'$ using $H$, $A$, and $C$. If $T' \neq T$, the implementation aborts immediately and discards all intermediate plaintext. Plaintext is never emitted or parsed prior to tag verification.
Plaintext (P) ----[ XOR with AES_K(Counter) ]----> Ciphertext (C)
                                                        |
Associated Data (A) --------------------------------+   |
                                                    v   v
                                            [ GHASH over GF(2^128) ]
                                                        |
Nonce (N) --------[ AES_K(J_0) ]----------------->[    XOR    ] ---> Auth Tag (T)

Composition Pitfalls: Combining Ciphers and MACs Independently

Before AEAD (mandated in modern protocols like TLS 1.3 per RFC 8446), engineers combined unauthenticated ciphers (e.g., AES-CBC) and MACs (e.g., HMAC-SHA256) manually. These compositions introduce critical failure modes:

ParadigmFlowSecurity GuaranteePrimary Failure Modes
Encrypt-and-MAC (SSHv2 legacy)$C = E(P)$, $T = M(P)$InsecureTag $T$ is computed on plaintext; deterministic MACs (like HMAC) leak whether two messages have identical plaintexts across sessions.
MAC-then-Encrypt (TLS 1.0–1.2 legacy)$T = M(P)$, $C = E(P \parallel T)$FragileDecryption must occur before verification. If the cipher requires padding (CBC), malformed padding errors versus invalid MAC errors create padding oracle side-channels (e.g., Lucky Thirteen, POODLE).
Encrypt-then-MAC (IPsec / AEAD standard)$C = E(P)$, $T = M(C \parallel A)$Cryptographically soundRequires strict separation: independent keys must be derived via HKDF (RFC 5869), and the MAC must explicitly cover the IV/nonce, AAD, and ciphertext.

Why Composition Fails in Practice

  1. Key Reuse: Using the same symmetric key $K$ for both AES and HMAC violates basic cryptographic separation principles; weaknesses in one algorithm compromise the internal state of the other.
  2. Unauthenticated Initialization Vectors: Developers frequently compute $\text{MAC}(C)$ instead of $\text{MAC}(\text{IV} \parallel C)$. In malleable modes like CBC or CTR, an attacker mutates the IV, altering the first decrypted block predictably without failing the MAC.
  3. Early Plaintext Release and Side Channels: If the verification step uses a non-constant-time byte comparison (memcmp), an adversary exploits timing to forge tags. If the application begins streaming or buffering decrypted data before the trailing MAC verification succeeds, memory safety vulnerabilities in downstream parsers can be triggered by unauthenticated ciphertext.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-13

How do KDFs and key separation improve a cryptographic design?

Answer

Assumptions, then the short answer

I'm deriving keys from a high-entropy secret: a 32-byte master key from a KMS, or an ECDH shared secret. Not a human password. Given that: HKDF (RFC 5869) turns one secret into as many independent keys as I need, each bound to a context string, and key separation means breaking one use doesn't hand over the others.

Mechanism

HKDF is extract-then-expand over HMAC-SHA256.

Extract: PRK = HMAC(salt, IKM). Salt is optional; RFC 5869 says if you omit it, use HashLen zero bytes: 32 for SHA-256. Extract concentrates entropy that's spread unevenly across the input.

Expand: T(1) = HMAC(PRK, info || 0x01), T(2) = HMAC(PRK, T(1) || info || 0x02), and OKM is T(1) || T(2) || ... truncated to L. Max L is 255 × HashLen = 8160 bytes for SHA-256. The blocks chain: T(2) consumes T(1).

The info field is the separation. Two keys from the same PRK differ only in info.

Trace

Python
import hmac, hashlib

def expand(prk: bytes, info: bytes, length: int) -> bytes:
    out, t, counter = b"", b"", 1
    while len(out) < length:
        t = hmac.new(prk, t + info + bytes([counter]), hashlib.sha256).digest()
        out += t
        counter += 1
    return out[:length]

Checked against Python 3.11.

  • expand(prk, b"myapp/v1/aead/tenant=42", 32): loop body runs once. t = HMAC(prk, b"" + info + b"\x01"), 32 bytes; len(out) == 32, loop exits; returns t. One HMAC call.
  • expand(prk, b"myapp/v1/mac/tenant=42", 32): same shape, different info, so different 32 bytes. One HMAC call.
  • expand(prk, info, 64): iteration 1 gives T(1) = HMAC(prk, info || 0x01); iteration 2 gives T(2) = HMAC(prk, T(1) || info || 0x02); out is 64 bytes, loop exits. Two HMAC calls, and T(2) is uncomputable without T(1).
purposeinfoLalgorithm
AEAD data keymyapp/v1/aead/tenant=4232AES-256-GCM
record MACmyapp/v1/mac/tenant=4232HMAC-SHA256
key wrappingmyapp/v1/wrap/tenant=4232AES-256-KW (RFC 3394)
exportmyapp/v1/export/tenant=4232AES-256-GCM

Failure modes

  • One key doing AES-GCM and HMAC. Cross-protocol attacks get easier, and GCM nonce reuse under a shared key is catastrophic.
  • Ambiguous info encoding: "tenant=1" + "2" and "tenant=12" collide. Length-prefix the fields or use a delimiter that can't appear in them.
  • Truncating to a length the algorithm doesn't expect: a 16-byte key handed to AES-256.
  • Root compromise exposes every descendant. Derivation is not isolation from root loss.
  • Feeding a password to HKDF: no stretching. Use Argon2id (OWASP minimum m=19 MiB, t=2, p=1) or PBKDF2-HMAC-SHA256 at 600,000 iterations, salt ≥16 bytes.
  • Changing info changes the keys. That's the rotation lever, so version the labels.

Testing: RFC 5869 test vectors, plus cross-language fixtures so a Go service and a Python service derive the same bytes.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-20

Generate and validate security tokens such as password resets or API keys.

Answer

Assumptions. A web app; tokens arrive by email link or Authorization header. The attacker can read your database and can hammer the endpoint. The token is a bearer capability: whoever holds it gets the action, so the whole design is about making it unguessable, un-replayable, and useless if the DB leaks.

Core answer. Generate 256 bits from the OS CSPRNG, store only a SHA-256 hash of it, redeem with a single conditional UPDATE so exactly one request wins, and bind the row to purpose, user, expiry and scope. Everything else is hardening.

Generation. secrets.token_urlsafe(32) (Python 3.6+) gives 32 random bytes rendered as 43 base64url characters, no padding, safe in URLs and headers. Don't use random. uuid4 is 122 bits and acceptable for online-only tokens, but the CSPRNG costs nothing. Encode with base64url or hex: standard base64's +, /, = break URLs and query parsing.

Why 256 bits. 2^256 ≈ 1.2e77. At 10^12 guesses/sec that's ~1e65 seconds. 128 bits (2^128 ≈ 3.4e38) is already enough for online attacks, at 1000 guesses/sec it's ~1e28 years, but 256 covers the offline case where the attacker holds your hash.

Storage. Store sha256(token), not the token. A DB dump then yields hashes, and inverting a 256-bit preimage is infeasible. Use SHA-256, not bcrypt/argon2: those exist to slow brute force of low-entropy secrets like passwords. A 256-bit token has no brute-forceable structure, so a slow KDF adds ~250 ms to every redemption for no security gain.

Redemption: the race. Two clicks on the same reset link arrive together. Both read used_at IS NULL, both write. Fix with a conditional update:

Python
def redeem(raw):
    h = hashlib.sha256(raw.encode()).hexdigest()
    row = db.execute(
        "UPDATE tokens SET used_at=? "
        "WHERE hash=? AND used_at IS NULL AND expires_at>? "
        "RETURNING user_id",
        (now(), h, now())).fetchone()
    return row  # None => unknown, expired, or already used

Trace: both requests compute the same h. The DB serializes the two UPDATEs. The first matches used_at IS NULL, sets it, returns the user. The second re-evaluates the predicate, finds used_at set, matches zero rows, returns None. Exactly one redemption. A read-then-write in application code has a window between the SELECT and the UPDATE: that's the bug this avoids.

Tradeoffs. Opaque + hashed row: revocable instantly, one DB round trip per check. Signed token (HMAC/JWT): stateless, no lookup, but revocation needs a denylist, which puts the lookup back. Use signed tokens for short-lived, high-volume, non-revocable things; opaque for password resets and API keys. Single-use for resets; API keys are reusable but rotatable: issue a new one, keep the old valid for a grace window, then delete.

Failure modes. Token in the Referer header when the reset page loads third-party assets: set Referrer-Policy: no-referrer. Token in access logs or APM: log the hash prefix only. Expiry compared with > vs >= at the boundary: test the exact second. Clock skew between app servers: use DB time or one clock. Enumeration: return the same body and status for unknown, expired and used tokens.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-17

What is forward secrecy, and where are its limits?

Answer

The 90-second answer

Forward secrecy means the traffic keys for a connection come from an ephemeral key exchange whose private values are deleted when the handshake ends. Record my traffic today, steal the server's long-term private key next year, and you still can't decrypt that recording: the key you stole only signed the handshake, it never derived the traffic keys.

TLS 1.3 (RFC 8446) made this the default by removing RSA key transport and static DH entirely. Every TLS 1.3 suite (TLS_AES_128_GCM_SHA256, TLS_AES_256_GCM_SHA384, TLS_CHACHA20_POLY1305_SHA256) uses (EC)DHE, so every TLS 1.3 connection is forward secret. In TLS 1.2 you have to check the suite, because TLS_RSA_WITH_AES_128_GCM_SHA256 is not: a leaked RSA key decrypts every recorded session that used it.

Suite / modeForward secret?Why
TLS 1.3 TLS_AES_128_GCM_SHA256Yesephemeral (EC)DHE; RSA key transport removed
TLS 1.2 ECDHE_RSA_*Yesephemeral ECDHE
TLS 1.2 TLS_RSA_WITH_AES_128_GCM_SHA256Notraffic keys wrapped to the server's RSA key
TLS 1.3 resumption, psk_dhe_keYesPSK mixed with a fresh ECDHE share
TLS 1.3 resumption, psk_keNokeys derived from the PSK alone
TLS 1.3 0-RTT early dataNokeys derived from the PSK

Where it stops

  1. The attacker got the traffic secrets, not just the ciphertext. SSLKEYLOGFILE, a core dump, a debugger on the process, a hypervisor snapshot: forward secrecy is irrelevant once the session keys are in hand. That's why suppressing secret logging is a real control.

  2. Endpoint compromise during the session. FS protects the past, not the present. Malware on the client or server reads plaintext before it's encrypted, and so does a TLS-terminating proxy holding the cleartext.

  3. Resumption. TLS 1.3 defines two PSK modes (RFC 8446 §4.2.9): psk_dhe_ke mixes in an ephemeral ECDHE share and stays forward secret; psk_ke alone does not. In TLS 1.2, session tickets (RFC 5077) encrypt session state under a server-held ticket key: compromise it and recorded ticket-based sessions decrypt. Rotate ticket keys on the order of hours, keeping the previous key only long enough to accept in-flight tickets.

  4. 0-RTT early data. Encrypted under keys derived from the PSK, so it doesn't inherit the 1-RTT handshake's forward secrecy, and it's replayable.

  5. Nonce reuse and AEAD limits. FS says nothing about nonce discipline: reusing a nonce with AES-GCM leaks the authentication key and permits forgery. And one key isn't used forever: RFC 8446 §5.5 caps AES-GCM at about 2^24.5 full-size records per key (roughly 24 million, a few hundred GB) before a KeyUpdate.

  6. Certificate misvalidation. A rogue or compromised CA, or a client that skips verification, puts the attacker inside the session. You handed them the keys; FS doesn't help.

  7. Weak ephemeral parameters. Logjam: 512-bit export DH and precomputed 1024-bit groups. Forward secret on paper, breakable in practice. Use 2048-bit+ FFDHE or X25519.

  8. Quantum. ECDHE falls to Shor's algorithm, so harvest-now-decrypt-later defeats FS against a future CRQC. Hybrid X25519MLKEM768 in TLS 1.3 is the current mitigation.

One framing worth keeping: FS is about the past. It does not heal the future after a compromise: that's post-compromise security, which something like the Double Ratchet provides and a plain TLS session does not.

What I'd actually do

Enforce TLS 1.3 with X25519 (hybrid PQ where the stack supports it), disable RSA key transport and static DH on any TLS 1.2 endpoint, rotate session ticket keys hourly, cap session lifetime, and treat SSLKEYLOGFILE and core dumps as secrets. In an incident the question isn't "was it forward secret": it's "did the attacker get the traffic secrets or an endpoint," because those are the two ways FS fails in practice.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-14

Explain the TLS 1.3 handshake at an engineering level.

Answer

TLS 1.3 full handshake is 1-RTT. Assume no client cert, no resumption, X25519, and TLS_AES_128_GCM_SHA256. The client speaks first; the server's first flight is encrypted after ServerHello.

FlightSenderContentsProtection
1ClientClientHello: legacy_version=0x0303, supported_versions=0x0304, key_share (X25519 public key), signature_algorithms, cipher_suitesplaintext
2ServerServerHello: key_share, cipher_suite; then EncryptedExtensions, Certificate, CertificateVerify, FinishedServerHello plaintext; rest AEAD under server handshake traffic secret
3ClientFinishedAEAD under client handshake traffic secret
4Bothapplication_dataAEAD under application traffic secrets

The client puts a key_share in ClientHello so the server can compute the shared secret without an extra round trip. The server picks one cipher suite from the five defined in RFC 8446, all AEAD: TLS_AES_128_GCM_SHA256, TLS_AES_256_GCM_SHA384, TLS_CHACHA20_POLY1305_SHA256, TLS_AES_128_CCM_SHA256, TLS_AES_128_CCM_8_SHA256. RSA key exchange, CBC, RC4, and SHA-1 are gone.

Key schedule, using HKDF-Extract and HKDF-Expand-Label:

  • ECDHE = X25519(client_private, server_public).
  • HKDF-Extract(salt=0, IKM=0) -> early_secret.
  • Derive-Secret(early_secret, "derived", "") -> derived_secret.
  • HKDF-Extract(salt=derived_secret, IKM=ECDHE) -> handshake_secret.
  • Derive-Secret(handshake_secret, "c hs traffic", transcript_hash(ClientHello..ServerHello)) -> client_handshake_traffic_secret; same for "s hs traffic".
  • Derive-Secret(handshake_secret, "derived", "") -> derived_secret2.
  • HKDF-Extract(salt=derived_secret2, IKM=0) -> master_secret.
  • Derive-Secret(master_secret, "c ap traffic", transcript_hash(ClientHello..server Finished)) -> client_application_traffic_secret_0; same for "s ap traffic".

Finished key = HKDF-Expand-Label(handshake_traffic_secret, "finished", "", Hash.length). Finished MAC = HMAC(finished_key, transcript_hash). AEAD nonce = static_iv XOR sequence_number. CertificateVerify signs the transcript with the certificate's private key, so the server proves possession of the key it presented.

Failure modes and detection:

  • HelloRetryRequest: if the client's key_share group is unacceptable, the server sends HRR with a cookie and supported_groups. The client resends ClientHello with a new key_share. Cost: one extra RTT. Detection: HRR is a ServerHello with a special random; the client must include it in the transcript hash.
  • Downgrade: if an attacker strips supported_versions and the server negotiates TLS 1.2, the server random ends with DOWNGRD\x01. The client checks that sentinel. A mismatched Finished transcript also aborts the handshake.
  • 0-RTT replay: early_data is encrypted with an early traffic secret derived from the PSK. An attacker can replay ClientHello plus early_data. Detection: the server sees the same ticket twice, or the application sees a duplicate order. Cost: disable 0-RTT for non-idempotent requests.
  • Certificate validation: the client aborts with bad_certificate, unknown_ca, certificate_expired, or access_denied. Detection: TLS alert.
  • Key compromise: ECDHE gives forward secrecy for the full handshake. 0-RTT early data does not get that if the PSK leaks.

Tradeoffs:

  • 0-RTT saves one RTT, often 50 ms cross-region, but is replayable. Use it only for idempotent GETs, not auth or payments. Disable it when the request changes state.
  • Resumption saves CPU and latency, but ticket keys must be rotated and the PSK protected.
  • Cipher suite choice: AES-GCM when AES-NI is available; ChaCha20-Poly1305 on mobile without AES-NI.
  • Client auth is optional. Mutual TLS adds CertificateRequest, client Certificate, and CertificateVerify. Use it when the server must authenticate the client before application data.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-16

When should a service use mutual TLS, and what does it not solve?

Answer

Core answer (first 90 seconds)

Reach for mTLS when both ends are workloads you can enroll, and the identity you need is which workload, not which user: east-west traffic inside a cluster, a service-to-service link to a partner, a device fleet terminating at an ingress. The precondition is that you can issue, distribute and rotate certificates to both sides. If you can't rotate, you've built a shared secret with a long expiry.

Skip it when the peer is a browser or a third party you can't enroll, when the identity that matters is the end user's, or when the question is "may this caller do this" rather than "who is this caller". mTLS establishes workload identity at the transport boundary. Everything above that boundary (authorization, delegation, data protection) is still yours to build.

When it's the right tool, and when it isn't

SituationmTLS?Why
Pod-to-pod inside one clusterYesBoth sides are enrolled by the platform CA; identity is the SPIFFE ID, not an IP that can be reused
Your service → partner API over the public internetYes, if the partner issues you a client certGives the partner a per-caller identity it can revoke without rotating a shared API key
Browser → your APINoUsers don't hold client certs; use OIDC or session tokens
Your service → a SaaS APINoThey authenticate you with an API key or SigV4; you can't enroll a client cert
"Only the billing service may call refunds"Not sufficientThat's authorization. mTLS gives you the input to a policy, not the policy

Worked trace: one call through an Istio mesh

  1. istiod issues the checkout pod an X.509 SVID with URI SAN = spiffe://cluster.local/ns/payments/sa/checkout, TTL 24h (Istio's workloadCertTtl default), signed by the mesh CA, and pushes it to the pod's Envoy over SDS.
  2. Checkout's Envoy opens TLS 1.3 to ledger's Envoy, presents the SVID, and proves possession of the private key in CertificateVerify. In TLS 1.3 that Certificate message is encrypted; in TLS 1.2 it went out in the clear, so a passive observer on the wire learned the client identity.
  3. Ledger's Envoy has require_client_certificate: true on its downstream context. It validates the chain against the mesh trust bundle, checks the URI SAN, and matches it against the PeerAuthentication (STRICT) and any AuthorizationPolicy.
  4. Envoy forwards to the app over loopback and sets x-forwarded-client-cert.
  5. Failure mode: if that app is also reachable on a NodePort or a pod IP from outside the mesh, anyone can send a request with a hand-written x-forwarded-client-cert and the app will believe it. The fix is to bind the app to loopback, or have the app verify the peer certificate itself instead of trusting the header.

What it does not solve

  • Authorization. A valid cert says who, not what. You still need a policy layer (Istio AuthorizationPolicy, OPA) that maps the SPIFFE ID to allowed methods and resources.
  • End-user identity and delegation. A workload cert carries no user. If the call is on behalf of a user, you need a token: OAuth 2.0 token exchange (RFC 8693) or a signed JWT: alongside the mTLS channel.
  • Confidentiality past the terminator. Mesh mTLS ends at the sidecar. Sidecar-to-app on loopback is plaintext, so anyone with pod access reads the payload.
  • Compromised endpoints. Malware that can read the private key file, or talk to the SDS socket, can impersonate the workload for the life of the certificate.
  • Revocation. There is no OCSP stapling for client certificates, and the mainstream stacks don't check revocation by default: Go's crypto/tls performs no CRL or OCSP fetch, and the JDK only checks when you set com.sun.net.ssl.checkRevocation=true and ocsp.enable=true, and then soft-fails. Your real revocation window is the certificate TTL.
  • Metadata. SNI, IPs and the certificate identity stay visible to the network even when the payload doesn't.
  • CA compromise. Whoever holds the mesh CA can mint any identity in it. SPIRE registration entries, or Istio's CA, are the actual boundary.

The number that decides the design

Revocation window ≈ certificate TTL. Istio's default is 24h, so a stolen workload key is usable for up to a day. SPIRE's default X.509 SVID TTL is 1h: a 24× smaller window, at the cost of 24 CA signatures per workload per day. Let's Encrypt's 90-day default is fine for a public server certificate and far too long for a workload identity you can't revoke. Pick the TTL from how fast you can detect and evict a compromised workload, not from how annoying rotation is.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-3

Design a versioned AEAD record format for sensitive application fields.

Answer

Core answer. Assume Postgres, a Python service, a KMS that hands out data keys, and a requirement to encrypt individual columns rather than whole rows so the rest stays indexable. I'd ship a self-describing binary record: a fixed 22-byte header, ciphertext, and a 16-byte tag. The header carries everything needed to decrypt except the key, and the header bytes are fed into the AEAD as associated data so they can't be edited without breaking the tag.

offsetsizefield
04magic AEF1
41format version = 1
51alg id: 1 = AES-256-GCM, 2 = XChaCha20-Poly1305
64key id, uint32 big-endian
1012nonce (24 bytes when alg id = 2)
22nciphertext
22+n16GCM/Poly1305 tag

AAD is the 22 header bytes followed by len(tenant)||tenant, len(record_type)||record_type, len(field)||field, each length a 2-byte big-endian prefix. That binds a ciphertext to one tenant, one record type, and one field, so a value can't be copied into another row and still decrypt.

Python
# Python 3.12, cryptography 42.x
import struct
from cryptography.hazmat.primitives.ciphers.aead import AESGCM

MAGIC, VER, ALG_GCM, NONCE_LEN, TAG_LEN = b"AEF1", 1, 1, 12, 16

def aad(tenant, rtype, field, header):
    lp = lambda b: struct.pack(">H", len(b)) + b
    return header + lp(tenant) + lp(rtype) + lp(field)

def seal(key_id, key, tenant, rtype, field, plaintext):
    nonce = next_nonce(key_id)                 # 12 bytes, counter-based
    header = MAGIC + bytes([VER, ALG_GCM]) + struct.pack(">I", key_id) + nonce
    ct = AESGCM(key).encrypt(nonce, plaintext, aad(tenant, rtype, field, header))
    return header + ct                         # ct = ciphertext || 16-byte tag

def open_(keyring, tenant, rtype, field, blob):
    if len(blob) < 22 + TAG_LEN: raise ValueError("truncated")
    if blob[:4] != MAGIC or blob[4] != VER or blob[5] != ALG_GCM:
        raise ValueError("unsupported")
    key_id = struct.unpack(">I", blob[6:10])[0]
    key = keyring.get(key_id)                  # no default fallback
    if key is None: raise ValueError("unknown key")
    return AESGCM(key).decrypt(blob[10:22], blob[22:],
                               aad(tenant, rtype, field, blob[:22]))

Trade-offs. Field-level beats envelope encryption when you still need to index or join on unencrypted columns; envelope is simpler and hides which fields exist, but you lose every query that isn't on the primary key. AES-256-GCM runs at 1–3 GB/s with AES-NI and is the default when you can enforce nonce discipline; XChaCha20-Poly1305 is constant-time in software and its 192-bit nonce is safe to generate randomly, so pick it on hosts without AES-NI or when you can't guarantee a counter. KMS-wrapped data keys give you audit and rotation but add a network round trip (single-digit ms); cache the unwrapped key in memory with a short TTL and refresh on key-id miss.

Failure modes. Nonce reuse under GCM leaks the XOR of two plaintexts and lets an attacker forge tags: detect it by persisting the counter and refusing to wrap. An AAD mismatch and a tampered ciphertext both surface as the same tag error, so return one generic failure and log key id plus field name for correlation. An unknown key id means a rollback or an old binary; fail closed rather than falling back to a default key. Truncation is caught by the length check before any decrypt call.

Nonce budget. NIST SP 800-38D caps random 96-bit nonces at 2^32 invocations per key for a 2^-32 collision bound. At 5,000 field writes/sec that is 4,294,967,296 / 5,000 ≈ 859,000 s ≈ 10 days, so either rotate keys weekly or use a 4-byte key epoch plus 8-byte counter nonce, which lifts the limit to 2^64 messages per key.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-4

How do you guarantee nonce safety for AES-GCM at scale?

Answer

The invariant is one sentence: for a given key, a nonce is used exactly once. Counters, prefixes, rotation: all of it is bookkeeping to make that true across processes, regions, restores and retries. If I can't guarantee it, I rotate the key before I write.

AES-GCM takes a 96-bit (12-byte) nonce. NIST SP 800-38D recommends exactly 96 bits; any other length gets run through GHASH to derive the counter block, which costs an extra pass and has its own constraints. So: 96 bits, always.

Two constructions, and the choice is about what you can guarantee.

Random 96-bit nonce. Safe only with a per-key cap. The birthday bound says that after 2^32 messages under one key, the collision probability is about 2^-32: that's the NIST number, and it's the one to defend. So: 2^32 messages per key, then rotate. Some shops use 2^31 for margin.

Deterministic counter. Split the 96 bits into a writer field and a counter: 32-bit writer ID + 64-bit counter, or 64-bit writer ID + 32-bit counter. The counter must be allocated atomically and never rewound. Concretely: a Postgres UPDATE ... RETURNING on a single row, a Redis INCR with AOF persistence, or a per-instance counter where the instance ID is unique and the counter is fsync'd before the write goes out.

Why reuse is catastrophic, not just bad: two messages with the same (key, nonce) let an attacker XOR the ciphertexts to recover the XOR of the plaintexts, and, worse, recover the GHASH subkey H, which lets them forge tags on arbitrary messages. It's a total break of the key, not a confidentiality downgrade.

Random path in Go:

Go
block, _ := aes.NewCipher(key)          // 32-byte key, rotated every 2^32 messages
gcm, _ := cipher.NewGCM(block)          // 12-byte nonce, 16-byte tag
nonce := make([]byte, gcm.NonceSize())  // 12
if _, err := rand.Read(nonce); err != nil { return err }
ct := gcm.Seal(nil, nonce, plaintext, aad)

crypto/rand is the OS CSPRNG. The counter you track is messages-per-key, not bytes.

Failure modes, and how each one shows up:

  • Restore from backup or VM snapshot. The counter rewinds to values already used. Keep the high-water mark outside the snapshot, a separate KMS-backed store, and refuse to start if the local counter is below it.
  • Fork. A child inherits the parent's RNG state or counter. On Linux, fork() after a rand.Read can duplicate. Re-seed in the child, or call getrandom(2) per use.
  • Multi-region writers. Two regions both start at counter 0 with the same key. Give each writer a distinct prefix, or give each region its own key.
  • Retries. Replaying the same (key, nonce, plaintext) is idempotent and safe. Replaying the same nonce with different plaintext is the break. Derive the nonce from a request ID so a retry reuses the nonce only when the plaintext is identical.
ConstructionNonceLimit per keyNeeds
Random96-bit from CSPRNG2^32 messages (~2^-32 collision)per-key counter, rotation
Counter32-bit writer + 64-bit counter2^64 messagesatomic allocation, no rewind
Per-message keyrandom nonce, key derived per messageeffectively unboundedKDF, e.g. HKDF(data key, message ID)

The third row is what the AWS Encryption SDK does: it derives a unique message key from the data key and the message ID, so the nonce can be random without a tight cap. TLS 1.3 is the same shape: per-connection key via HKDF, the 64-bit record sequence number XORed with the connection IV as the nonce, and a KeyUpdate before the sequence number wraps.

Rotation and metrics: rotate when messages-per-key hits the cap, or when the counter field is about to wrap. Emit a messages-per-key counter and alert at 80% of the cap. Log the key ID and the count: never the nonce next to the key.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-10

Define the complete lifecycle for an application encryption key.

Answer

The 90-second answer

A key's lifecycle is a state machine, not a checklist: define → generate → distribute → use → rotate → suspend → destroy, with one invariant. A key version is never destroyed while any ciphertext still references it. In practice you run envelope encryption: a KMS-held key-encryption key (KEK) never leaves the HSM, and per-object data keys (DEKs) are generated by it, used locally, and stored wrapped beside the ciphertext. That split is what makes rotation cheap: you re-wrap DEKs, not data.

Define before generating. Owner, purpose, algorithm and strength (AES-256-GCM for symmetric data; RSA-2048+ or ECDSA P-256 for asymmetric), data classification and tenant scope, allowed operations (encrypt/decrypt/sign, never export), lifetime, and the compromise plan. Scope is the decision that bites: one KEK per tenant per region bounds blast radius but multiplies key count and rotation work.

Generate and distribute. Generate inside the cryptographic boundary: AWS KMS, GCP KMS, Azure Key Vault, or Vault Transit with an HSM-backed seal. Callers get an IAM key policy or Vault policy granting kms:GenerateDataKey/Decrypt or transit/encrypt/decrypt; they never receive key bytes. Workload identity (IRSA, SPIFFE, a GCP service account) authenticates the caller.

Use. GenerateDataKey returns a plaintext DEK and the same DEK wrapped under the KEK. Cache the plaintext DEK in memory for its lifetime: a KMS call is a network round trip, and AWS KMS's default shared quota is 5,500 symmetric operations/second per account per Region, so per-record calls throttle you.

Rotate. AWS KMS automatic rotation (default 365 days, configurable 90–2560) creates new backing material under the same key ID and retains the old material for decryption. Vault Transit does the same with rotate plus min_decryption_version and min_encryption_version. The mechanism that avoids downtime: ciphertext carries its key version, new writes use the latest version, old reads still decrypt, and a background job re-wraps or re-encrypts old objects. Vault's transit/rewrap re-encrypts a ciphertext under the newest version without exposing plaintext.

StateMeaningTransition
Pending / pre-activationmaterial generated, not yet usableenable
Enabledencrypt + decryptdisable, rotate
Decrypt-onlyold version, reads onlydestroy once no ciphertext references it
Disabled / suspendedno operations, reversiblere-enable or schedule deletion
Pending deletionAWS KMS 7–30 day window (default 30)cancel or destroy
Destroyedmaterial gone, irreversible—

Failure modes. (1) Destroying a version still referenced by an S3 object, a Kafka topic, or a database backup: detect by scanning ciphertext metadata for key versions before scheduling deletion; the KMS deletion window exists to catch exactly this. (2) A leaked DEK in a heap dump or log: detect with secret scanning and by alerting on Decrypt calls from unexpected principals. (3) Rotation that never finishes: track the fraction of objects on the current version; if it plateaus, the re-wrap job is failing silently. (4) Throttling: alarm on KMS ThrottlingException.

Trade-offs. Escrow is a real decision, not a hedge. Escrow (split knowledge, dual control: Shamir shares held by two custodians) buys recovery from a lost KEK but creates a second copy of the crown jewels and a target. Skip it when the data is re-derivable or the KEK sits in a managed HSM with its own durability; require it when losing the key means losing regulated records. Rotation interval is the same trade: shorter bounds exposure, more re-wrap cost and more versions to track.

Destroy. Confirm retention and legal holds, prove no backup, replica, queue, or rollback artifact references the key, then destroy. AWS KMS makes this irreversible after the waiting period; Vault requires deletion_allowed and correct archive_version handling.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-9

Explain and design envelope encryption for a multi-service platform.

Answer

Assumptions first. Services run in one cloud region against a managed KMS/HSM (AWS KMS, GCP Cloud KMS, or Vault Transit); data at rest lives in object storage and a relational DB; the threat model is a compromised service or leaked service credentials, not a compromised KMS. If the KMS operator is in scope, you need an HSM with quorum-controlled key use, and that changes the design.

Core answer. Envelope encryption splits the key into two layers so the key that touches bulk data never leaves the process, and the key that protects it never leaves the KMS.

  • Per object, batch, or tenant, call GenerateDataKey. It returns a plaintext DEK and the same DEK encrypted under a KEK (the CiphertextBlob). The plaintext DEK is used once with an AEAD, AES-256-GCM or ChaCha20-Poly1305, then dropped.
  • Store ciphertext, the wrapped DEK, and metadata: KEK id, KEK version, algorithm, nonce, AAD.
  • Bind context with AAD: tenant id, resource id, key version. A ciphertext moved to another tenant fails to decrypt instead of silently succeeding.
  • On read, Decrypt the wrapped DEK, then open the payload.

Why two layers: the KEK never leaves the KMS, so a compromised service can only unwrap DEKs its identity is authorized for, and only while the grant exists. Rotating the KEK is a rewrap of DEK blobs: no bulk data re-encryption. Rotating a DEK does require re-encrypting the data it protects, so DEK lifetime is a policy choice, not a free operation.

Scoping.

ScopeUnwrapsBlast radiusUse when
object1 per readone objectlarge objects, strict isolation
batch1 per N objectsN objectshigh write volume, quota/cost bound
tenant1 per cache misswhole tenantread-heavy, per-tenant isolation acceptable

Worked arithmetic (hypothetical; AWS KMS list price $0.03 per 10,000 requests, default quota 5,500 symmetric requests/sec per account per Region). 10,000 writes/sec with a fresh DEK each is 864M KMS calls/day = $2,592/day, and it blows past the 5,500 rps quota into throttling. Batch 1,000 objects per DEK: 10 calls/sec = 864k calls/day = $2.59/day, comfortably under quota. That gap is the entire reason batching exists.

Trace of a read.

  1. Service reads blob + wrapped DEK + metadata from storage.
  2. Cache lookup on (tenant, KEK version). Miss → Decrypt(wrappedDEK, EncryptionContext={tenant, resource}), p50 ~5 ms, p99 ~25 ms cross-AZ (hypothetical).
  3. AES-256-GCM open with AAD = tenant|resource|key_version. Tag mismatch raises InvalidCiphertextException: a hard failure, never a partial read.
  4. Cache the plaintext DEK with a 5-minute TTL and a bounded entry count.

Failure modes.

  • KMS throttling. Writes stall; write-path p99 climbs from ~10 ms to seconds. Detect via ThrottlingException count and write-path p99. Fix by batching, caching, or a quota increase.
  • Regional KMS outage. Cached DEKs keep reads working until TTL; new writes fail immediately. Detect via KMS API error rate. Cost is bounded by TTL: a 5-minute TTL buys 5 minutes of read availability, then hard failure.
  • Grant revocation. Revocation is not instant: a cached plaintext DEK keeps working until TTL expires. Set TTL to your revocation SLA, and don't cache DEKs for high-sensitivity tenants.
  • AAD mismatch on restore. Restoring a tenant's data under a new tenant id fails to decrypt. Catch it with a restore test in CI; otherwise you discover it mid-incident.
  • Partial rewrap. Some DEK blobs sit on the new KEK version, some on the old. Metadata must carry the version and readers must accept both until the sweep finishes.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-8

Compare disk, database, and application-level encryption.

Answer

The 90-second answer

All three encrypt the same bytes. They differ in where plaintext exists and who can reach it. Disk encryption puts the boundary at the block device, database encryption at the storage engine or the column, application encryption at the process holding the key. Choose the layer by naming who you don't trust: the person who steals the drive, the DBA, or your own storage operator. Layers stack, but each one you add buys a specific threat and costs query capability.

Disk (LUKS2, EBS)Database (TDE / Always Encrypted)Application (envelope, AES-256-GCM)
Cipheraes-xts-plain64, 512-bit key (LUKS2 default); EBS uses AES-256-XTSTDE: AES-256 by default since SQL Server 2016; InnoDB tablespace encryption via keyring pluginAES-256-GCM, 12-byte nonce + 16-byte tag
Plaintext visible toroot, hypervisor, anything with the mounted volumeany session with SELECT; the DBAonly the process holding the DEK
Protectsstolen or decommissioned media, offline snapshotsdata files, backups, WAL/redostorage operators, DBAs, backups, logs
BreaksnothingTDE: nothing. Always Encrypted randomized: WHERE, ORDER BY, LIKE, FKs fail with an operand type clashequality, range, sort, join, unique, unless you add a blind index
Key custodyTPM/clevis, or KMS for EBScertificate in master / Azure Key VaultKMS CMK → per-tenant DEK

PostgreSQL has no native TDE (through 17); the usual answer is volume encryption plus pgcrypto or the Percona pg_tde extension for columns.

Failure modes, with detection

  1. TDE certificate loss. A TDE backup is encrypted with the DEK, which is wrapped by a certificate in master. Lose that certificate and RESTORE DATABASE fails with error 33111, "Cannot find server certificate with thumbprint 0x…". The backup file is intact and useless. Only a monthly restore drill into a scratch instance catches this.
  2. KMS key deletion. Deleting an AWS KMS CMK has a 7–30 day waiting period, after which every DEK it wrapped is unrecoverable: EBS volumes won't attach, envelope-encrypted columns won't decrypt. Alarm on KMSInvalidStateException from Decrypt, and decrypt a canary row every minute.
  3. Deterministic leakage. Deterministic encryption lets you index and join, but equal plaintexts produce equal ciphertexts: for a low-cardinality column like country, a leaked backup reveals most of the distribution. Randomized hides that and kills the queries. Decide per column, not per table.
  4. Rotation without versioning. If the ciphertext carries no key version, rotating the KEK makes old rows undecryptable. Put key_version in the header, keep old KEKs decrypt-only, and run a nightly job that decrypts the oldest row per version.
  5. Metadata leakage. Disk encryption leaks file sizes and access times; TDE leaks row counts, index sizes and query timing; app-level leaks ciphertext length unless you pad. A 16-digit SSN becomes 44 bytes: length is a signal.

Worked artefact

Python
# Python 3.12, cryptography 42.x, boto3
import boto3, os
from cryptography.hazmat.primitives.ciphers.aead import AESGCM

kms = boto3.client("kms")

def encrypt_field(tenant_id: str, field: str, plaintext: bytes) -> bytes:
    dek = kms.generate_data_key(KeyId=CMK_ALIAS, KeySpec="AES_256")
    nonce = os.urandom(12)
    aad = f"{tenant_id}:{field}".encode()
    ct = AESGCM(dek["Plaintext"]).encrypt(nonce, plaintext, aad)
    return dek["CiphertextBlob"] + nonce + ct

Trace the AAD binding: a row for tenant A is stored with AAD "A:ssn". If a query bug passes tenant B, the AAD becomes "B:ssn" and AESGCM.decrypt raises InvalidTag instead of returning tenant A's data. That turns a tenant-isolation bug into a hard failure rather than a silent leak: the reason to bind context into the AAD rather than encrypting the value alone.

Overhead arithmetic: GCM adds 28 bytes per value (12 nonce + 16 tag). 50M rows × 28 B = 1.4 GB of pure overhead, plus the opaque KMS blob per row. A blind index for equality lookups adds a 32-byte HMAC-SHA256 per indexed field.

When not to use it. Application-level encryption is the wrong choice if analysts need ad-hoc range queries on the column: you'll end up decrypting into a warehouse, which puts plaintext back on a system you didn't secure. Disk encryption is the wrong answer when the threat model is a curious DBA.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-11

Rotate encryption keys online without losing data or producing mixed-state ambiguity.

Answer

Assumptions I'd state before answering. Envelope encryption: a KMS-held key-encryption key (KEK) wraps a data key (DEK), and the stored blob is {key_version, wrapped_dek, nonce, ciphertext}. I'll assume Postgres for the record store, AWS KMS for the KEK, AES-256-GCM for the DEK. If your blobs don't carry a key version today, that backfill is the first migration and the one that actually hurts.

The core answer: don't rotate in place. Make the key version a property of the ciphertext, not of the service. Then "which key" is never ambiguous: a reader looks at the blob, not at a global config pointer. New writes go to version N+1; versions ≤ N stay enabled for decrypt only. Migration is a separate, resumable background job.

Why that beats a swap: a global "current key" pointer makes every in-flight request during the swap a coin flip, and a rollback has to guess which records were touched. Version-in-blob makes the state per-record and the rollback trivial.

The migration worker. Idempotent, checkpointed, compare-and-swap guarded:

SQL
UPDATE documents
   SET wrapped_dek = :new_wrapped_dek,
       key_version = :new_version
 WHERE id = :id
   AND key_version = :old_version;   -- 0 rows if someone already moved it

The AND key_version = :old_version is the whole trick: a stale worker that read the row before a concurrent write re-encrypted it matches zero rows and skips. No lost update, and no lock held across the KMS call.

Checkpoint every 10,000 rows in a migration_checkpoint(table_name, last_id, started_at) row; on restart, resume from last_id. Batch 500 rows per transaction so a crash costs at most one batch of rework.

KMS budget. AWS KMS's default symmetric cryptographic-operation quota is 5,500 requests per second per account per Region (check Service Quotas; it's adjustable). You should not be near it: with envelope encryption you call KMS once per DEK, not per record. If a DEK covers 10,000 records, a 100M-record table needs 10,000 Decrypt+Encrypt pairs, not 100M. Cap the worker at roughly 30% of quota and back off on ThrottlingException with jittered exponential backoff.

The trade-off you should name. Three options, and the deciding question is what are you rotating away from:

approachcostrotates the DEK?when to pick
Re-wrap only (new KEK, same DEK)metadata UPDATE, no plaintext touchednoscheduled KEK rotation
Full re-encrypt (new DEK + new ciphertext)O(bytes), plaintext in memoryyesDEK suspected compromised
Lazy re-encrypt on readspread out, no scanyes, eventuallyno hard retirement deadline

Lazy is the one people reach for and the one that bites: a record nobody reads stays on the old key forever, so you can never retire it. If compliance gives you a date, you need the background scan.

Failure modes and how you see them. Stale worker clobbering a newer write: the CAS above; alert when the rows-updated-equals-zero rate spikes. Worker crash: the checkpoint row; alert if last_id hasn't advanced in 15 minutes. KMS throttling: ThrottlingException count in CloudWatch. A reader that meets an unknown key_version must fail closed, not fall back to a default key; that fallback is the mixed-state bug, and it's a code-review rule, not a runtime one.

Rollback and retirement. Rollback means stop the worker and keep old keys enabled. Records already on N+1 stay there; dual-read covers both. Retire an old key only when SELECT count(*) FROM documents WHERE key_version = :old returns 0, the object store has been fully scanned, and a restore drill from the oldest backup decrypts cleanly.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-23

Choose a key-isolation strategy for a multi-tenant SaaS product.

Answer

The 90-second answer

I'd run envelope encryption with one KMS key per tenant as the key-encryption key (KEK), and a data key per object or batch under it. Assumptions I'd confirm before committing: tenants are external and a contract or regulator requires provable isolation or per-tenant deletion; the tenant count is hundreds to low tens of thousands; and request volume makes a KMS call per operation unattractive. If tenants are internal or the data is non-sensitive, one key per environment per service is simpler, and I'd say so up front.

Why that shape

Write path: GenerateDataKey on the tenant's KEK with EncryptionContext {"tenant": tid, "table": "invoices"} returns a plaintext DEK plus a wrapped copy. Encrypt locally with AES-256-GCM using the same context as AAD, and store wrapped DEK, ciphertext, and key ARN. Read path: Decrypt the wrapped DEK with the same context, then decrypt locally. Per-tenant KEKs give you two independent checks: the key policy can deny any caller not scoped to that tenant, and the AAD check fails on any context mismatch. With one global key the policy check disappears - isolation then rests entirely on the AAD, so a single code path that drops the tenant id from the context becomes a silent cross-tenant read.

Arithmetic

AWS KMS charges $1/month per customer-managed key and $0.03 per 10,000 requests. Ten thousand tenants is $10,000/month in keys before any traffic. A KMS call per read at 2,000 rps is 2,000 * 2.592e6 = 5.18e9 requests/month, roughly $15,500, and it runs against an account-level quota near 10,000 symmetric operations per second per Region, shared across all keys (the current figure is on the KMS request-quotas page and is raisable). Caching DEKs in the app for five minutes collapses that to one call per active tenant per epoch: 10,000 active tenants is about 33 rps.

strategyblast radius on key compromiserevoke / crypto-shredkey cost at 10k tenants
one key per accountevery tenantre-encrypt everything$1/mo
one key per servicethat service's tenantsper service only~$10/mo
per-tenant KEK + DEKone tenantdisable or delete the KEK, effective within DEK TTL$10,000/mo

Failure modes and how they show up

  • Key-reference substitution. Decrypting with the key ARN stored on the row makes a cross-tenant read succeed silently. Derive the ARN from the authenticated principal - a validated token claim, or an IAM principal tag mapped into the request - never from the record. Detect by grouping CloudTrail Decrypt events per caller principal and key ARN and alarming when a caller not scoped to that tenant touches the key.
  • Throttling. One hot tenant plus retries on ThrottlingException turns into account-wide failures. Watch the ThrottlingException rate and wrap latency p99; answer with the DEK cache, jittered backoff, and a quota increase.
  • Revocation lag. A five-minute plaintext DEK cache keeps serving a disabled key for up to five minutes. Set TTL to 0 for tenants with contractual cut-off terms and publish the bound either way. Deleting a KMS key has a 7-30 day waiting period (default 30) before destroy, so disable-and-alarm on DisableKey and ScheduleKeyDeletion events gives instant cutoff with a rollback window.
  • Incomplete shredding. Deleting a tenant KEK only covers what sits under it - backups, S3 object versions, search indexes, and any shared analytics key survive. Enumerate per-tenant key usage from CloudTrail and storage inventory before promising deletion.

Below roughly 100 tenants with no isolation clause, one key per environment is the right call. In the high tens of thousands, Vault Transit derived keys (one physical key, a derived key per context) sidesteps per-key cost and key-count ceilings, and tenant-held keys make your availability depend on their custody decisions.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-21

What are the security and product tradeoffs of searching encrypted fields?

Answer

The 90-second answer

The question only has an answer once you fix two things: the query set the product actually needs, and the attacker you're defending against. Assume the honest-but-curious case: the database operator, or anyone holding a stolen backup, sees ciphertext, index values and query patterns, but not the application's keys. Under that model, every scheme that lets you search ciphertext leaks something specific. There is no transparent encrypted search. So the job is to pick the least-leaky scheme that covers the queries you truly need, and if none does, change the requirement. The product side of the tradeoff is exactly which queries you are willing to give up.

Why each scheme leaks what it leaks

Deterministic encryption maps equal plaintexts to equal ciphertexts. That is the point, it makes equality searchable, and it is also the leak: an attacker groups ciphertexts by value and runs frequency analysis. On a low-entropy domain (a boolean flag, a status enum, a 9-digit SSN) frequency analysis becomes a dictionary attack: encrypt the candidate set yourself and match.

Order-preserving or order-revealing encryption preserves rank, so the ciphertext distribution mirrors the plaintext distribution. An attacker who knows the plaintext distribution (US ages, salaries, timestamps) maps ciphertext ranks back to values. Naveed, Kamara and Wright (CCS 2015) demonstrated this inference attack against property-preserving encrypted databases; it is why OPE is not a serious option for sensitive fields.

A blind index is a keyed hash of the normalized plaintext, truncated to N bits, stored beside the ciphertext. It gives exact match and leaks equality plus frequency, exactly like deterministic encryption, and adds a collision leak from truncation.

Searchable symmetric encryption hides values but leaks the access pattern: which documents match a query, and whether the same query repeats. Cash et al. (CCS 2015) showed leakage-abuse attacks that recover plaintext from that pattern alone.

Options

SchemeQuery supportedLeakageUse when
Randomized encryption, decrypt after fetchnone server-sidenone beyond row countresult set is small; you accept no server-side sort or pagination
Search a non-sensitive projectionwhatever the projection supportsprojection is plaintextthe searchable attribute isn't the secret
Tokenization vaultexact match via tokenvault is a high-value target; round-trip latencyPCI-style card data, few query shapes
Deterministic encryption / blind indexexact matchequality, frequency, truncation collisionslow-cardinality or high-entropy fields
MongoDB Queryable Encryption (GA in 7.0)equality; range in later releasesencrypted index access patternyou're on MongoDB and want the index managed for you

CipherSweet (PHP) is the reference blind-index implementation: per-field keys derived from a master key, keyed hash truncated to a configurable bit length, compound indexes for multi-column match.

Artefacts

Blind index, normalization first:

Python
import hmac, hashlib, unicodedata

def blind_index(value: str, field_key: bytes, bits: int = 32) -> int:
    norm = unicodedata.normalize("NFKC", value).strip().casefold()
    digest = hmac.new(field_key, norm.encode("utf-8"), hashlib.sha256).digest()
    return int.from_bytes(digest[:4], "big") >> (32 - bits)

Trace: "Alice@Example.com " → NFKC → strip → casefold → "alice@example.com"; "alice@example.com" normalizes to the same string, so both produce the same 32-bit index. "alice@example.org" produces a different one. The output is a 32-bit integer. Normalization is what makes the index stable across input variants, and it is where bugs live: if one writer stores "Alice@Example.com" unnormalized, its index never matches.

Truncation arithmetic: a 32-bit index reaches a 50% collision probability at about 77,000 distinct values (birthday bound, 1.177·√2³²). At 16 bits it collides at roughly 300 distinct values. Collisions mean two plaintexts share an index, so a query returns false positives: the app must re-check the decrypted value.

Failure modes

Rotation: rotating the index key requires re-indexing every row, because the index must match the new key. A job that re-encrypts the column but not the index leaves rows silently unsearchable: queries return empty, not errors. Detect by recomputing indexes and counting mismatches.

Deletion: crypto-shredding a per-tenant key makes ciphertext unreadable, but if the blind index key is shared, the index entries survive and still leak equality across the corpus. Per-tenant index keys fix this and multiply key management by tenant count.

Multi-tenancy: one shared index key turns any tenant's query into a cross-tenant equality oracle. A tenant can confirm another tenant's value exists. Scope index keys per tenant.

Enumeration: an attacker with query access brute-forces low-entropy fields. A 9-digit SSN is ~10⁹ candidates; at a hypothetical 10,000 queries/sec that is under 28 hours. Rate-limit per principal, and key per tenant so one tenant's enumeration doesn't confirm another's data.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-7

Design cryptographic protection for a system storing regulated personal data.

Answer

The 90-second answer. Start from who can read plaintext, not from algorithms. Four layers, each answering a different adversary: TLS 1.3 on every hop kills network interception; volume encryption (LUKS/dm-crypt, cloud volume encryption) kills stolen media and decommissioned disks; envelope encryption with per-record data keys kills database dumps and snapshot exfiltration; field-level AEAD with context binding is the only layer that narrows the DBA/operator threat, and it costs you query capability. Pick the deepest layer the threat model actually requires, because each step down costs more.

Concretely: a root KEK per region lives in an HSM-backed KMS (FIPS 140-3 Level 3) and never leaves it. Each record or field gets a fresh 256-bit DEK; you encrypt the field with AES-256-GCM (96-bit nonce, 128-bit tag) and store the wrapped DEK beside the ciphertext. Wrapping is a KMS Encrypt call: AWS KMS caps direct plaintext at 4 KB, which is exactly why you wrap a DEK instead of calling KMS per field. Rotate the KEK annually (AWS KMS default 365 days, configurable 90–2560); rotation re-wraps DEKs, it does not re-encrypt data, and that is the whole point of the hierarchy.

Why context binding matters. Pass tenant ID, field name, row ID and key version as AAD. Without it, an attacker with UPDATE rights can move a low-privilege user's encrypted SSN into a high-privilege row and GCM still verifies. With AAD, decryption fails. That is the mechanism, not a slogan.

Nonce discipline. GCM nonce reuse under one key leaks the GHASH authentication key and permits forgery. Either use a per-DEK counter, or use random 96-bit nonces and rotate the DEK before roughly 2^32 messages under it. If you cannot guarantee uniqueness, use AES-GCM-SIV (RFC 8452) or XChaCha20-Poly1305 (192-bit nonce).

Trade-offs, where to stop.

PlacementStopsCost
TLS 1.3passive network capturenone, mandatory
Volume encryptionstolen disk, snapshot leak~0, transparent
Envelope (DEK/KEK)DB dump, backup theftKMS latency + quota
Field AEAD + AADDBA, operator, cross-row swapno range or equality queries
Deterministic / blind indexequality search on encryptedfrequency leakage

Deciding criterion: if the DBA is not in your threat model, stop at envelope encryption. Field-level encryption is not worth it when you need range queries, sorting or analytics on the column: you end up building a blind index that leaks access patterns, or decrypting into an analytics store that reintroduces the risk. Say that out loud in the interview.

Failure modes and detection.

  • KMS throttling: per-key request quotas (AWS KMS defaults run 5,500–50,000 req/s by region). Symptom: ThrottlingException and p99 write latency climbing. Mitigation: cache DEKs in memory with a short TTL, never a KMS call per row.
  • Nonce reuse: detect with a monotonic counter assertion; a duplicate is a page, not a log line.
  • Crypto-shredding that does not shred: destroying a DEK leaves wrapped copies in backups and replicas. Detection: a deletion test that restores the oldest backup and asserts decryption fails.
  • Key-version drift: ciphertext with no key-version tag becomes undecryptable after rotation. Bind the version in AAD and assert on read.

Legal access. Key custody is a policy decision: if the KMS sits in the same jurisdiction as the data, a lawful order can compel unwrapping. Cross-region KEKs under separate custody is the lever; document it rather than pretending encryption defeats compulsion.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-5

Design password storage for a new authentication service.

Answer

Assumptions first. New service, no legacy hashes to carry, we own the database, and the threat is an offline attack on a stolen dump, not a live attacker who already owns the app server. If the app server is compromised, the pepper is the only thing still standing.

The answer. Argon2id at OWASP's baseline: m=19456 KiB (19 MiB), t=2, p=1, a 16-byte salt from a CSPRNG, 32-byte output. Store the full PHC string, $argon2id$v=19$m=19456,t=2,p=1$<salt>$<hash>, so parameters travel with the record and you can rehash on login when you raise them. Tune upward until p50 verification is ~250 ms on production hardware and stop before 1 s; that is the budget users tolerate and the number you defend in review.

Why Argon2id: memory-hardness is what makes GPU and ASIC cracking expensive. 19 MiB per guess multiplied across a GPU's parallelism is real cost; a pure-iteration function like PBKDF2 lets an attacker buy the same work with cheap silicon.

Capacity is the failure mode people miss. 19 MiB × concurrent logins is resident memory. 200 concurrent logins = 3.7 GiB of transient allocation, and an unauthenticated endpoint that allocates 19 MiB per request is a DoS primitive. Cap concurrency at the hasher, queue the rest, and rate-limit per IP and per account before the request reaches the hash.

Pepper. 32 random bytes in KMS/HSM, not in the database, applied as HMAC-SHA-256(pepper, password) before Argon2id, or as Argon2's secret parameter if your library exposes it. It turns a DB-only dump into a non-event. The cost: rotating it requires re-hashing every record on next login, and losing it locks everyone out. Write the recovery path down before you ship.

Alternatives, and when to pick them. scrypt (N=2^17, r=8, p=1) if Argon2id is unavailable in your runtime. bcrypt with work factor ≥10 only if you must, and pre-hash with SHA-256 then base64, because bcrypt silently truncates at 72 bytes. PBKDF2-HMAC-SHA256 at 600,000 iterations as the FIPS-constrained fallback.

Input handling. Normalize with NFKC, accept at least 64 characters, never truncate silently, and skip composition rules: NIST SP 800-63B dropped them. Verify with the library's constant-time compare, never ==.

Online attacks. Rate limit, breached-password check at registration and reset (HIBP k-anonymity range API), MFA. Hashing does nothing against a live credential-stuffing run.

What would change the decision. A FIPS 140-3 requirement pushes you to PBKDF2. A passkey rollout demotes the password path to a fallback and lets you raise the cost. A sub-100 ms latency SLA on a shared host pushes you to scrypt with lower memory, or to a dedicated hashing tier.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-6

Migrate a legacy password-hash database without forcing every user offline.

Answer

First I'd clarify what we can still verify. If the legacy store is unsalted MD5 or SHA-1, we can verify by hashing the supplied password the same way. If it used a pepper that is gone, we cannot verify at all and those accounts must reset. I'd assume we can run the legacy verifier in-process, we have a current hasher, and we can add a version column or parse it from the stored string.

The migration is lazy. On successful legacy verification, rehash with the current algorithm and replace the stored value in the same transaction that marks the login successful. Never downgrade a current hash. Keep the legacy verifier behind an interface so it can be deleted once the version count reaches zero.

Mechanically: read the stored string, parse the version. If it's current, verify with the current hasher. If it's legacy, verify with the legacy verifier. On success, compute a new hash with current parameters (for example argon2id v=19 m=19456,t=2,p=1 or bcrypt $2b$12$) and update the row. Use constant-time comparison. Make the update conditional on the old hash still being present, so a concurrent login doesn't clobber a newer rehash.

Here's the shape:

Python
def login(user, password):
    stored = user.password_hash
    if verify_current(stored, password):
        return ok
    if verify_legacy(stored, password):
        new = hash_current(password)
        update_password_hash(user.id, new, expected=stored)
        return ok
    return fail
Legacy formatExample prefixVerificationAction
Unsalted MD532 hex charsmd5(password)rehash on login; force reset if breach
SHA-140 hex charssha1(password)same
bcrypt$2b$12$...bcrypt checkrehash if cost < 12
PBKDF2pbkdf2_sha256$600000$...PBKDF2-HMAC-SHA256rehash if iterations < 600000
argon2id$argon2id$v=19$m=19456,t=2,p=1$...argon2 verifycurrent

Trade-offs: lazy migration is right when the legacy algorithm is verifiable and the risk is moderate. Forced reset is right when the pepper is lost, the algorithm is broken (unsalted MD5), or there's an active breach. For inactive accounts, lazy migration leaves them legacy until next login; if that's unacceptable, stage a reset. Dual-write is not worth it: it doubles the attack surface and the migration path.

Failure modes: rehash stampede. After deploy, every login does an expensive hash; CPU saturates and auth p99 spikes. Detect via auth latency and CPU; mitigate with rate limits, canary rollout, and a queue. Partial update: verification succeeds but the DB write fails; the user logs in but stays legacy. Detect via version counters; no security regression. Truncation mismatch: legacy truncated to 8 chars; full password fails. Detect via failed-login spike for migrated users; handle by trying the truncated variant during migration. Pepper rotation: old pepper unavailable; all legacy verifications fail. Detect via sudden 100% legacy failure; reset. Enumeration: timing difference between legacy and current; detect via timing distributions; use a dummy hash.

Tests: golden fixtures for each legacy format, malformed strings, concurrent logins, transaction rollback, performance under load, enumeration timing. Metrics: count rows by version, rehash success rate, legacy verification failures. Credentials never enter logs or analytics.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-18

Design certificate renewal and emergency replacement without outage.

Answer

Assumptions: public HTTPS behind a load balancer, certs from a public CA (Let's Encrypt, 90-day default), internal mTLS for service-to-service, automation via cert-manager or certbot with ACME (RFC 8555). DNS-01 challenge.

Core answer. Renew at T-30 days: one-third of the 90-day lifetime. Deploy the new cert alongside the old one, verify the full chain and hostname on every hop, then retire the old cert after the longest session-ticket or DNS TTL. For emergency replacement, assume the old key is compromised: revoke it, issue a new cert with a new key, deploy broadly, and monitor CT logs. Revocation is not instant: OCSP soft-fail means some clients will accept the old cert until it expires, so plan for that window.

Renewal design. Overlap works because TLS servers select a cert by SNI. You can't serve two certs for the same name to the same client in one handshake, but you can roll out to a subset of nodes (canary) and verify, or serve both RSA and ECDSA certs via multiple ssl_certificate directives in nginx: clients pick based on supported algorithms. Session resumption is the trap: clients with a session ticket can resume without a full handshake, so they may not see the new cert until the ticket expires. nginx ssl_session_timeout defaults to 5m but can be 1h; wait at least that long before retiring the old cert.

Verify the chain and hostname with openssl s_client -connect host:443 -servername name -showcerts and openssl verify -CAfile chain.pem cert.pem. Check OCSP stapling with openssl s_client -status. Check expiry with openssl x509 -enddate -noout. Run synthetic probes from external locations.

Monitor with Prometheus blackbox_exporter probe_ssl_earliest_cert_expiry (seconds until expiry). Alert if < 7 days. cert-manager exposes certmanager_certificate_expiration_timestamp_seconds. Monitor CT logs (crt.sh, certstream) for any cert for your domains not issued by your automation.

Emergency replacement. Contain: identify which key, issuer, and endpoints. Create clean material: new key (RSA 2048 or ECDSA P-256), new CSR, new cert. Deploy broadly: all nodes, all regions, all CDNs. Revoke the old cert via ACME revoke-cert. But revocation is advisory: Chrome uses CRLSets (not real-time OCSP), Firefox does OCSP with soft-fail. Assume the old cert is trusted until expiry. Assess: check CT logs for unexpected issuance, check TLS handshake logs for use of the old cert after revocation. Rollback only if the new cert is broken and the old cert is not compromised; if compromised, fix forward.

Trade-offs. Short-lived (90-day or 6-day) vs long-lived (1-year): short-lived reduces the compromise window but requires robust automation; a failed renewal causes an outage. Long-lived reduces automation burden but increases exposure. Deciding criteria: if you have mature automation and canary deploys, go short-lived; if not, use longer and invest in monitoring. Public CA vs internal CA: public CA gives ubiquity but rate limits (Let's Encrypt: 50 certs/domain/week, 5 duplicate/week) and dependency on an external CA. Internal CA gives control but you must distribute trust anchors to all clients; a compromised internal CA is worse. Revocation vs short lifetimes: revocation is unreliable; short lifetimes are the only reliable way to limit exposure.

Failure modes with detection.

  • Automation failure: cert-manager Ready condition false, alert on expiry < 7 days. Blast radius: all services using that cert. Cost: outage.
  • Clock skew: ACME JWS timestamp rejected, cert appears expired. Detection: NTP monitoring. Blast radius: renewal fails.
  • OCSP soft-fail: OCSP responder down, clients with soft-fail continue; must-staple clients fail. Detection: monitor OCSP responder and stapling freshness. Blast radius: must-staple clients get errors.
  • SNI mismatch: load balancer missing cert for new SNI, clients get default cert. Detection: synthetic probes with -servername. Blast radius: clients see wrong cert.
  • Revocation not propagated: OCSP caching, CRL distribution. Detection: monitor OCSP responses for revoked status. Blast radius: old cert accepted until expiry.
  • Rate limits: ACME error rateLimited. Detection: monitor ACME errors. Blast radius: cannot issue new cert; need backup CA.

Worked timeline. Let's Encrypt 90-day cert. T-90: issue. T-30: renew, deploy to 10% of nodes, verify with openssl s_client, then 100%. T-29: retire old cert after 24h overlap. T-0: old cert expires. Emergency: key compromise at T-45. Revoke old cert, issue new cert, deploy in 15 minutes, monitor CT logs for 30 days. Blast radius: clients that don't check revocation (soft-fail) may accept the old cert until T-0 (45 days). If must-staple was used, clients enforcing it reject immediately; otherwise, accept the risk and monitor.

| Approach | Renewal window | Compromise window | Automation burden | Failure mode | | 90-day | T-30 | up to 90 days | moderate | renewal failure -> outage | | 6-day | T-2 | up to 6 days | high | renewal failure -> outage | | 1-year | T-30 | up to 1 year | low | long exposure |

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-19

How do you sign and verify release artifacts securely?

Answer

The 90-second version

Assume we ship container images to a registry and run them on Kubernetes, CI is GitHub Actions, and the target is SLSA Build Level 3. My answer: sign the image digest, using an identity only the release workflow can obtain, log the signature so it can't be backdated, and verify identity plus provenance at admission, not merely "a signature exists."

Signing

Build in a hosted, isolated builder that emits SLSA provenance as an in-toto attestation in a DSSE envelope. Then sign keyless with cosign: it asks Fulcio for a certificate bound to the workflow's OIDC identity, something like https://github.com/acme/api/.github/workflows/release.yml@refs/tags/v1.2.3, valid for 10 minutes. The private key exists in memory for that window, so there is no long-lived secret to exfiltrate. The signature, certificate and Rekor inclusion proof are pushed to the registry as an OCI artifact tagged sha256-<digest>.sig.

If you can't go keyless, put the key in an HSM or KMS (AWS KMS asymmetric, PKCS#11) so it never leaves, and use TUF-style threshold signing so one compromised key can't sign alone.

Verifying

cosign verify \
  --certificate-identity-regexp '^https://github\.com/acme/api/\.github/workflows/release\.yml@refs/tags/v.*$' \
  --certificate-oidc-issuer https://token.actions.githubusercontent.com \
  registry.example.com/acme/api@sha256:9f2c1e...

cosign verify-attestation --type slsaprovenance \
  --certificate-identity-regexp '...' \
  --certificate-oidc-issuer https://token.actions.githubusercontent.com \
  registry.example.com/acme/api@sha256:9f2c1e...

Since cosign 2.0 those identity flags are mandatory for keyless verification: that's the point. Then an admission controller (Sigstore policy-controller, Kyverno verifyImages, or Gatekeeper) runs the same check on every pod, so nothing unsigned reaches a node.

What each check actually buys you

CheckProvesDoes not prove
Digest matchBytes unchanged since signingCode is safe
Signature validSome key signed itIt was the release identity
Cert identity + issuerThe release workflow signed itThe build was reproducible
SLSA provenanceBuilt by that builder from that commitDependencies are clean
Rekor entryThe signature existed at a logged timeAnything about intent

Failure modes

Verifying a tag instead of a digest lets an attacker repush the same tag. Verifying a signature without pinning identity lets any Fulcio certificate from any GitHub repo pass: the classic mistake. A long-lived key in a CI secret signs anything forever once leaked. And a validly signed old image with a known CVE is still a rollback: admission needs a monotonic version check, not just signature validity.

On compromise: rotate the TUF root with threshold, revoke, re-sign, reconcile the fleet. Notation/Notary v2 is the OCI-native alternative if you're not on Sigstore.

A signature binds bytes to an identity under policy. It never answers "is this code safe": source review, dependency scanning and tests still do.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-15

How do hybrid post-quantum key exchange mechanisms such as X25519 combined with ML-KEM integrate into TLS 1.3, and what are their operational trade-offs?

Answer

Hybrid key exchange integrates a post-quantum Key Encapsulation Mechanism (such as ML-KEM-768) alongside a classical ephemeral Diffie-Hellman group (such as X25519) within a single TLS 1.3 handshake. The primary goal is defense against "store-now-decrypt-later" (harvest-now-decrypt-later) attacks: an adversary recording ciphertext today cannot decrypt it with a future cryptanalytically relevant quantum computer (CRQC), while the classical component guarantees security if the newer lattice scheme is found vulnerable.

Handshake & Key Schedule Integration

In TLS 1.3 (RFC 8446), key agreement takes place in the supported_groups and key_share extensions. Hybrid mechanisms are assigned designated NamedGroup identifiers (for example, X25519MLKEM768):

  1. ClientHello: The client advertises the hybrid group in supported_groups and provides a concatenated KeyShareEntry in key_share. This payload carries both the 32-byte X25519 public key and the ML-KEM encapsulation key (1,184 bytes for ML-KEM-768).
  2. ServerHello: The server chooses the hybrid group and responds with its own concatenated share: a 32-byte X25519 ephemeral public key and an ML-KEM ciphertext (1,088 bytes for ML-KEM-768).
  3. Secret Combination: Both endpoints compute the classical shared secret ($SS_{classical}$, 32 bytes) and decapsulate the post-quantum shared secret ($SS_{PQ}$, 32 bytes). In standard implementations, these secrets are concatenated ($SS_{hybrid} = SS_{classical} \parallel SS_{PQ}$, 64 bytes) and fed into the standard TLS 1.3 key schedule via HKDF-Extract (RFC 5869):

$$\text{Early Secret} = \text{HKDF-Extract}(0, 0)$$ $$\text{Handshake Secret} = \text{HKDF-Extract}(\text{Derive-Secret}(\text{Early Secret}, \text{"derived"}, \epsilon), SS_{hybrid})$$

Because HKDF behaves as a pseudo-random function over its input keying material, breaking only one of the underlying components provides zero advantage in distinguishing or deriving the Handshake Secret.

Packet Sizes and Network Trade-offs

MechanismClient Key ShareServer Key ShareCombined OverheadTCP Handshake Impact
Pure X2551932 bytes32 bytes64 bytesFits inside a single 1500-byte MTU TCP segment
X25519 + ML-KEM-7681,216 bytes1,120 bytes2,336 bytesClientHello expands to ~1.6–2.0 KB; ServerHello to ~1.4–1.8 KB

Failure Modes & Edge Cases

  • IP Fragmentation and Middlebox Drops: A standard Ethernet MTU is 1500 bytes (leaving ~1420–1460 bytes for TCP payloads). A hybrid ClientHello routinely exceeds 1.5 KB when combined with existing SNI, ALPN, and session ticket extensions. This forces the ClientHello across two TCP packets or requires IP fragmentation. Middleboxes that perform stateful packet inspection on single-segment initial packets or drop out-of-order IP fragments will silently drop these handshakes, causing client connection timeouts.
  • QUIC / HTTP/3 Initial Packet Constraints: QUIC RFC 9000 mandates that client initial datagrams be padded to at least 1,200 bytes, but amplification limits restrict servers from sending more than 3x the bytes received until the client address is validated. An enlarged ClientHello spanning multiple UDP packets increases packet loss exposure during connection establishment.
  • Computational Cost: While ML-KEM key generation, encapsulation, and decapsulation are computationally fast (often comparable to or faster than scalar multiplication on Curve25519), the I/O throughput and memory cache pressure from moving multi-kilobyte keys at hundreds of thousands of handshakes per second shift bottlenecks toward memory bus bandwidth and NIC serialization.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-22

What are the practical performance and compatibility implications of transitioning transport encryption to Post-Quantum Cryptography algorithms like ML-KEM and ML-DSA?

Answer

Post-Quantum Cryptography (PQC) shifts transport security from discrete logarithm and factoring assumptions (ECDH, RSA) to lattice-based problems (Module-LWE for ML-KEM, Module-SIS/LWE for ML-DSA). The core operational trade-off is not CPU throughput, lattice operations are computationally fast, but payload size and network fragmentation.

Size and Latency Dynamics

In classical TLS 1.3 (RFC 8446), an X25519 public key and ciphertext/shared secret exchange is 32 bytes each. In contrast, ML-KEM-768 requires an 1,184-byte public key and a 1,088-byte ciphertext. While ML-KEM encapsulation and decapsulation execute in tens of microseconds (often faster than ECDH scalar multiplication), injecting a ~1.2 KB public key into the TLS ClientHello key_share extension pushes the initial packet dangerously close to standard Ethernet Maximum Transmission Units (MTU = 1500 bytes; MSS = 1460 bytes for IPv4, 1440 for IPv6).

When ClientHello includes existing extensions (SNI, ALPN, Session Tickets) alongside an ML-KEM or hybrid key share, the handshake payload exceeds a single TCP segment. This induces:

  1. Multi-packet ClientHello: If packet loss hits either fragment during the initial TCP slow-start flight, connection establishment incurs an RTO/spurious retransmit penalty (often adding 200 ms+ latency).
  2. Middlebox interference: Legacy stateful firewalls and NAT gateways frequently drop fragmented initial UDP/TCP packets or reject TLS records exceeding standard historical thresholds.

Key Encapsulation vs. Authentication

AlgorithmPrimitive TypePublic Key SizeCiphertext / Signature SizeHandshake Stage Impact
X25519Classical KEX32 B32 BFits in single TCP segment / initial QUIC datagram
ML-KEM-768Lattice KEM1,184 B1,088 BMulti-packet ClientHello on typical MTUs
Ed25519Classical Signature32 B64 BNegligible certificate chain footprint
ML-DSA-65Lattice Signature1,952 B3,309 BBloats TLS Certificate / CertificateVerify message (~7–10 KB with chain)

Migration Architecture: Hybrid Key Exchange

Because standalone PQC primitives carry algorithmic novelty risks, transition architectures implement hybrid key exchange (e.g., X25519MLKEM768). The endpoints generate both an X25519 ephemeral keypair and an ML-KEM-768 keypair.

Following RFC 5869 / TLS 1.3 key derivation patterns, the resulting shared secret is concatenated and passed to the KDF extract step:

SS_hybrid = SS_classical (32 B) || SS_mlkem (32 B)
Early_Secret = HKDF-Extract(0, 0)
Handshake_Secret = HKDF-Extract(Derive-Secret(Early_Secret, "derived", ""), SS_hybrid)

This guarantees that an adversary capable of breaking Module-LWE cannot decrypt recorded traffic unless they also break discrete log over Curve25519 (preserving pre-quantum forward secrecy against Store-Now-Decrypt-Later threats), and vice versa.

Authentication and Deployment Strategy

Deploying ML-DSA for identity authentication (server certificates) is substantially more disruptive than KEM deployment. A 3-certificate chain using ML-DSA-65 adds >15 KB of verification data to the server response, exceeding TCP initial congestion windows (initcwnd = 10 packets ≈ 14.6 KB) and degrading QUIC amplification limit checks (RFC 9000 limits unvalidated response data to 3x client payload). Therefore, practical migration prioritizes hybrid ML-KEM for forward secrecy first, while retaining classical ECDSA/RSA for authentication until intermediate infrastructure adapts to larger certificates.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-24

Build cryptographic agility into a long-lived application protocol.

Answer

Assumptions. Both ends can't be upgraded in lockstep; stored data outlives the code that wrote it; the attacker can read and modify wire bytes and stored blobs. If any of those is false, most of this is over-engineering.

Core answer. Agility is three separable things, and conflating them is the usual failure. First, every ciphertext and every handshake names its algorithm in an authenticated field. Second, a policy layer decides which names are acceptable. Third, migration is a data problem with a reader-before-writer ordering, not a config flip. Key rotation is not algorithm migration: rotating RSA-2048 to another RSA-2048 key changes nothing about the algorithm risk.

Python
# Python 3.12, cryptography 42.x
import json, os
from cryptography.hazmat.primitives.ciphers.aead import AESGCM, ChaCha20Poly1305

ALLOWED = {"A256GCM": (AESGCM, 32), "C20P": (ChaCha20Poly1305, 32)}

def seal(keyring, plaintext, alg="A256GCM"):
    cls, klen = ALLOWED[alg]              # KeyError -> unknown alg, fail closed
    key = keyring[alg]
    assert len(key) == klen
    nonce = os.urandom(12)
    aad = alg.encode()                    # alg id is authenticated, not just parsed
    ct = cls(key).encrypt(nonce, plaintext, aad)
    return json.dumps({"v": 1, "alg": alg, "n": nonce.hex(), "ct": ct.hex()})

def open_(keyring, blob):
    m = json.loads(blob)
    if m["v"] != 1:
        raise ValueError("unknown envelope version")
    cls, _ = ALLOWED[m["alg"]]           # fail closed on unknown/deprecated
    aad = m["alg"].encode()
    return cls(keyring[m["alg"]]).decrypt(
        bytes.fromhex(m["n"]), bytes.fromhex(m["ct"]), aad)

Trace. seal writes {"v":1,"alg":"A256GCM",...} with the tag computed over AAD b"A256GCM". An attacker flips alg to "C20P": open_ selects ChaCha20Poly1305 and builds AAD b"C20P", so the tag check fails and decrypt raises InvalidTag. Flipping alg to "RC4" raises KeyError before any crypto runs. Both fail closed; neither silently downgrades.

Negotiation. Copy TLS 1.3 (RFC 8446): the client sends supported_versions and signature_algorithms, the server picks from its allowlist, and the client rejects anything it didn't offer. TLS_FALLBACK_SCSV (RFC 7507) exists because pre-1.3 servers negotiated down silently. The client's list is a hint; the server's allowlist is the policy.

Failure modes, with detection and cost.

  • JOSE algorithm confusion. A verifier that dispatches on the token's own alg accepts HS256 signed with the RSA public key as the HMAC secret. Detect by asserting alg matches the key's family before verifying, and alerting on any mismatch. Cost: full auth bypass with no key compromise.
  • Silent downgrade. A legacy client offers only a retired suite and the server accepts it. Detect with a per-suite counter on the negotiated result; alert on any suite outside the allowlist. Cost: the migration is defeated while dashboards stay green.
  • Orphaned ciphertext. Retiring an algorithm before every blob is re-wrapped. Detect with a decrypt-failure counter keyed by envelope version; a non-zero rate on the old version blocks retirement. Cost: permanent data loss. The one failure you cannot roll back.
  • Library default drift. An envelope that stores no algorithm ID and leans on the library default. OpenSSL 3.x moved to providers and changed defaults. Detect by pinning the algorithm explicitly and asserting on read. Cost: silent, and only found at restore time.

Trade-offs. Negotiation vs. pinning: negotiation keeps old clients alive, pinning shrinks the attack surface. Decide by whether you control both ends within one release cycle, if you do, pin. Dual-write vs. lazy re-encryption on read: dual-write doubles write cost and storage for the window but gives a clean cutover; lazy leaves a tail, and cold data is exactly what never gets read. Decide by the cold fraction; if it's high, dual-write. Hybrid vs. pure post-quantum: hybrid (X25519 + ML-KEM-768, draft-ietf-tls-ecdhe-mlkem) survives ML-KEM being broken; pure is smaller. Decide by whether that's in your threat model.

Arithmetic. ML-KEM-768 encapsulation keys are 1184 bytes and ciphertexts 1088 bytes (FIPS 203), against 32 bytes for X25519. ML-DSA-65 signatures are 3309 bytes (FIPS 204), against roughly 64–72 bytes for ECDSA P-256. A three-certificate chain signed with ML-DSA-65 adds about 10 KB to the handshake, which exceeds the initial congestion window and can cost a round trip. Budget for bytes, not CPU. NIST IR 8547 (initial public draft, Nov 2024) proposes deprecating RSA-2048 and ECC by 2030 and disallowing them after 2035: that is the deadline your inventory is racing.

Decision criterion. Ship the versioned, authenticated envelope and the allowlist first. They are the only parts that are cheap to add later; which algorithms you run and when you retire them is a policy change you can make once the envelope exists.

Curated: · Written: · Reviewed:

Difficulty: Hard