Cryptography Fundamentals Questions
Core concepts and vocabulary of cryptography: confidentiality, integrity, authentication, and non-repudiation; the difference between symmetric and asymmetric primitives; and how standard algorithms, libraries, and protocols fit together. Covers threat models, common standards, and applying primitives and cryptographic libraries correctly to real-world security problems. The entry point for the cryptography track.
A microservice needs to encrypt small high-frequency messages with minimal latency. Evaluate trade-offs between using symmetric AEAD (AES-GCM), hybrid encryption per recipient, or public-key authenticated encryption. Consider throughput, key management complexity, bandwidth, and security properties (confidentiality, authentication). Recommend an approach and justify.
Sample Answer
Direct answer
For small, high-frequency messages, use symmetric authenticated encryption with associated data
(AEAD), such as AES in Galois/Counter Mode (AES-GCM) or ChaCha20-Poly1305, on a per-recipient
session key that was established once via a public-key exchange, not per message. Doing the
expensive public-key operation on every message is the one option that does not scale; doing it
once per session and then paying only symmetric-cipher cost per message is the standard answer to
this trade-off.
Structured elaboration
| Option | Per-message cost | Key management | Bandwidth overhead |
|---|---|---|---|
| Symmetric AEAD with a shared session key | One block-cipher pass plus a fixed 16-byte tag | Needs a session key already established and rotated | Smallest: nonce (12 bytes) + 16-byte tag |
| Hybrid: wrap a fresh symmetric key per message with the recipient's public key | Adds one public-key encryption per message on top of the symmetric pass | Simplest trust model (only public keys needed) but a new wrapped-key blob every message | Largest: a public-key-sized blob (hundreds of bytes) added to every message |
| Public-key authenticated encryption directly on the payload | A public-key operation sized to the whole message, not just a key | Simplest key distribution | Largest and slowest; public-key primitives are not built for bulk data |
- Confidentiality and authentication. AEAD gives you both in one pass: the tag fails to verify
if either the ciphertext or any associated data was altered, so you do not need a separate
Message Authentication Code (MAC). - Key establishment. Do the public-key work exactly once per session, using an
Elliptic-Curve Diffie-Hellman (ECDH) exchange, and derive the AEAD key from that shared secret
with a Key Derivation Function (KDF) such as HKDF. Rotate the session key on a schedule (minutes
to hours, depending on how sensitive the traffic is) rather than per message. - Nonce discipline. AES-GCM's security depends entirely on never reusing a nonce under the
same key. At high message rates, a per-connection counter is safer than relying on randomness
alone; if that is operationally awkward, use a nonce-misuse-resistant mode (AES-GCM-SIV) as
insurance rather than as the primary design.
Worked example
A checkout service sends roughly one small event per user action to a downstream fraud-scoring
service. Design: on connection setup, run ECDH once between the two services to get a shared
secret, derive a 256-bit AEAD key with HKDF, then for every event call
AESGCM(key).encrypt(nonce, event_bytes, aad=service_id) with a monotonically increasing 96-bit
counter as the nonce. Per-message cost is now one AES-GCM pass over a few hundred bytes and a
16-byte tag; the ECDH and HKDF steps run once per connection lifetime, not once per event, which is
exactly what keeps the per-message path cheap regardless of message volume.
Trade-offs & pitfalls
- Hybrid-per-message and public-key-per-message both add a public-key operation to the hot path;
at high frequency this dominates cost and is the wrong trade for latency-sensitive traffic. - A shared long-lived session key is only as strong as its rotation policy: an attacker who
compromises it can read every message encrypted under it until rotation, so weigh rotation
frequency against key-exchange overhead. - Common wrong turn: choosing hybrid encryption "for simplicity" without noticing that generating
and wrapping a fresh symmetric key every message reintroduces the exact public-key cost per
message you were trying to avoid.
Case study: you are responsible for migrating multiple services from custom in-house cryptographic code to libsodium. Draft a migration plan that includes inventory of primitives and usages, mapping to libsodium equivalents, interop and compatibility testing, key rotation and data migration strategies, rollout phases, audit and review processes, and rollback plans. Identify key risks and mitigations.
Sample Answer
Direct answer
Treat migrating from custom crypto to libsodium like any high-blast-radius infrastructure change: sequence it so a mistake is caught in a low-traffic environment before it touches production data, keep the library swap and any key rotation as two independently reversible steps rather than one combined change, and never remove the old decrypt path until every byte of live data is confirmed migrated.
Inventory
Catalog every custom-crypto call site across the migrating services: encryption, hashing, MAC, key generation, and random-number generation. For each, record the primitive in use, key size, mode, where the keys currently live, and whether random values actually come from a CSPRNG (cryptographically secure pseudorandom number generator) rather than something weaker. This inventory is the migration's real scope, don't start mapping to libsodium APIs before every call site is accounted for.
Mapping to libsodium equivalents
| Current custom code | libsodium equivalent | Notes |
|---|---|---|
| Custom AES-CBC plus a separate HMAC | crypto_secretbox (XSalsa20-Poly1305 AEAD) | Combines confidentiality and integrity in one call, removing the "did you use encrypt-then-MAC correctly" question entirely |
| Hand-rolled password hashing | crypto_pwhash (Argon2id) | Memory-hard, tunable work factor |
| Seeded or custom "random" key generation | randombytes_buf | Backed by the OS CSPRNG |
| Hand-rolled signature scheme | crypto_sign (Ed25519) | Deterministic signatures, no per-signature nonce to get wrong |
Interop and compatibility testing
The old scheme's ciphertext layout will not match libsodium's framing, so plan for dual-read support: every service must keep decrypting data written in the old format while writing only in the new format going forward. Tag every record with an explicit format-version identifier so a reader always knows which decrypt path applies to it. Validate the new path against a large sample of production-shaped data in staging before flipping any write path in production.
Key rotation and data migration
Don't re-encrypt everything in one shot. For large, slow-moving datasets, re-encrypt lazily on next read or write ("re-encrypt on touch"); for data with a hard compliance deadline to leave the old format, run an explicit background migration job. Either way, track progress with a per-record version flag so a partially completed migration is always safe to resume.
Rollout phases
Canary a single low-traffic service first, writing in the new format behind a feature flag while retaining the ability to fully revert to the old code path. Expand to more services only after the canary has run clean for a defined bake-in period. Remove the old crypto dependency and its decrypt path only once all live data is confirmed migrated or explicitly deprecated.
Audit and review
Independent code review of every changed call site against the mapping table, not just "did it compile." Run the migrated code against libsodium's own known-answer test vectors to confirm the integration layer didn't introduce a bug. Require a security sign-off before the old library is actually removed.
Rollback plan
Keep the old library and its decrypt path available, gated by the format-version flag, until the migration is independently verified complete. That means a bug found post-rollout can be mitigated by reverting only the write path, without needing an emergency mass-decrypt of already-migrated data.
Key risks and mitigations
- Silent format incompatibility (old data becomes unreadable): mitigated by the version tag plus the mandatory dual-read requirement above.
- Changing the library and the key material in the same step conflates two variables in one change, making a failure hard to attribute. Mitigate by doing them as separate, independently reversible steps, first swap the library while re-wrapping existing keys unchanged, then rotate keys as a distinct follow-up change.
- Team unfamiliarity with a new API introduces fresh implementation bugs even when the underlying primitives are safer. Mitigate with mandatory review against the mapping table and the known-answer test suite, not functional tests alone.
Explain the Random Oracle Model (ROM) and how it differs from the standard model in security proofs. Discuss practical implications when a real-world scheme has a proof in the ROM but uses a concrete hash function as the instantiation. Provide one example of where an ROM proof does not guarantee security in practice and outline why.
Sample Answer
Direct answer
The Random Oracle Model (ROM) treats a hash function as an idealized black box that returns a truly random output for every new input, and a consistent, repeated output for a repeated input. The standard model requires a security proof to hold using only the hash function's precisely stated, concrete mathematical properties. A proof "in the ROM" is a proof about that idealized object, not automatically a proof about any specific real hash function you plug in.
How the two differ
In an ROM proof, every party, including the security reduction itself, queries a shared random oracle instead of computing a real hash function; each new input gets a uniformly random answer, recorded so repeated inputs get the same answer. This lets proofs use techniques unavailable in the standard model, such as "programming" the oracle's answers or reading which queries an attacker made. A standard-model proof has to go through using the primitive's actual definition (collision resistance, preimage resistance) with no idealization, which is typically much harder, and many efficient, deployed schemes have no known standard-model proof at all.
The practical implication
A scheme proven secure in the ROM is only guaranteed secure as long as its hash function behaves like a random oracle for the specific ways the proof uses it. Substituting any concrete hash function, SHA-256, SHA-3, anything, is an assumption, not a consequence of the proof, because no real, efficiently computable function can actually be a random oracle: a true random oracle needs an unbounded table of independent random answers, and a real hash function is a fixed, describable algorithm.
Where an ROM proof does not guarantee real-world security
Canetti, Goldreich, and Halevi (1998) constructed a digital signature scheme, contrived but formally valid, that is provably secure in the ROM, and proved that for any concrete function substituted for the random oracle, the resulting scheme becomes insecure. This doesn't mean any specific deployed ROM-proved scheme, RSA-based full-domain-hash signatures, or Fiat-Shamir-transformed proofs, is broken; most of them remain unbroken after decades of scrutiny. What it proves is that the step from "secure in the ROM" to "secure with a real hash function" is a genuine, unclosable logical gap rather than a technicality, which is why ROM-proved schemes still warrant extra practical scrutiny (choice of hash function, resistance to known structural attacks) beyond "the proof says it's fine."
Trade-offs and pitfalls
Standard-model security is strictly stronger evidence but often means a slower scheme, a more complex construction, or no known efficient construction at all. ROM proofs let you use efficient, widely deployed constructions (Fiat-Shamir-based signatures, OAEP padding, full-domain hash) with a well-understood, if theoretically imperfect, security argument, which is why most of applied cryptography deliberately lives here. The pitfall is treating "proven secure in the ROM" as equivalent to "proven secure" without qualification, and separately, an ROM proof is only as strong as the specific oracle queries the reduction relies on; it doesn't automatically rule out every way a real hash function could be misused, a length-extension attack against a Merkle-Damgard hash used naively as a MAC is a case the ROM abstraction does not prevent unless the proof specifically accounts for it.
Give a high-level walkthrough of a TLS handshake: what happens at each step, which cryptographic primitives are used where (certificates, asymmetric key exchange, symmetric session keys, MAC/AEAD), and what properties TLS is actually trying to guarantee. What's one common way this can fail in practice?
Sample Answer
Direct answer
A TLS (Transport Layer Security) handshake lets a client and server who have never met agree
on a shared symmetric key, authenticate the server (and optionally the client), and start
exchanging data, with confidentiality, integrity, and (with modern configuration) forward
secrecy. It works by combining asymmetric key exchange and certificate-based identity checks
up front, then switching to fast symmetric encryption for the actual traffic.
Structured elaboration
sequenceDiagram
participant C as Client
participant S as Server
C->>S: ClientHello (supported versions, cipher suites, key share, random)
S->>C: ServerHello (chosen cipher suite, key share, random)
S->>C: Certificate (server public key, signed by a CA)
S->>C: Finished (proves possession of the certificate's private key)
Note over C,S: Both derive the same shared secret via ECDHE, then a session key via a KDF
C->>S: Finished (handshake integrity check)
C->>S: Application data (encrypted with the negotiated AEAD cipher)
S->>C: Application data (encrypted with the negotiated AEAD cipher)
- ClientHello / ServerHello: negotiate protocol version, cipher suite, and exchange
ephemeral key-exchange material (an elliptic-curve public value for ECDHE) plus random
nonces that feed the key derivation. - Certificate: the server presents its certificate, a public key bound to an identity and
signed by a certificate authority (CA), so the client can authenticate who it is actually
talking to (see PKI/certificate chains for how that trust is validated). - Key derivation: both sides combine the ECDHE exchange output through a KDF (key
derivation function) to produce the actual symmetric session keys, never sending the
session key itself over the wire. - Application data: all subsequent traffic is encrypted and authenticated with an AEAD
cipher (typically AES-GCM or ChaCha20-Poly1305) under the derived session key; older TLS
versions could instead pair a plain block cipher with a separate MAC (message
authentication code) computed over each record, a split that AEAD replaces with one
combined operation. - Properties TLS is guaranteeing: confidentiality (only the endpoints can read the data),
integrity/authenticity (tampering is detected), server authentication (the certificate
chain proves identity), and, with an ephemeral key-exchange suite, forward secrecy.
Worked example / common failure
The most common real-world failure is not a cryptographic break, it is trust management:
an expired certificate. Everything about the handshake's math can be flawless and the
connection will still be rejected (or a warning shown) the moment the leaf certificate's
validity window has passed, because clients check expiration as part of chain validation
before they will trust the negotiated key exchange at all. This is a frequent cause of
sudden, otherwise-unexplained outages, and is why certificate expiry monitoring is treated as
an operational, not just a security, concern.
Trade-offs & pitfalls
- TLS 1.3 (RFC 8446) simplified this flow and removed insecure options entirely (no more
static-RSA key exchange, no more weak cipher suites), which is why upgrading from TLS 1.2
is itself a meaningful security improvement, not just a version bump. - A valid, unexpired certificate chain proves identity, it does not by itself prove the
identity is trustworthy; certificate validation and business-level trust are separate
concerns.
Compare an encrypt-then-MAC construction (e.g. AES-CBC + HMAC) against a dedicated AEAD cipher like AES-GCM for protecting an HTTP API payload. Cover performance, hardware acceleration, streaming support, IV/nonce requirements, and where each approach is more likely to be implemented incorrectly.
Sample Answer
Direct answer
Both encrypt-then-MAC (AES-CBC plus a separately computed HMAC) and a dedicated AEAD cipher
like AES-GCM protect confidentiality and integrity together, but AEAD bundles them into one
call with one failure mode to get right, while encrypt-then-MAC is two separate primitives you
must sequence correctly yourself. For a new HTTP API payload, AES-GCM is the default choice
unless there's a specific reason to prefer the older combination.
Structured elaboration
- Performance and hardware acceleration: AES-GCM benefits from dedicated CPU instructions
(AES-NI plus carryless multiplication for the authentication step), making it very fast on
essentially all modern server and mobile hardware. Encrypt-then-MAC with AES-CBC plus HMAC
requires two separate passes over the data (one for the cipher, one for the MAC), roughly
doubling the work, though both individual pieces can still be hardware-accelerated. - Streaming support: HMAC can be updated incrementally as data arrives, since it just
needs the full message to compute a final digest, which suits streaming reasonably well.
AES-GCM also supports incremental processing but has an internal limit on how much data one
nonce can safely encrypt before the underlying counter risks exhaustion; for very large or
long-lived streams under one key, that limit needs to be tracked. - IV/nonce requirements: CBC needs an unpredictable IV per message (repetition leaks
structure but is not immediately catastrophic). GCM needs a nonce that is never reused
under the same key (repetition is catastrophic: see the nonce-reuse mechanics above, up to
full key-material exposure). - Where each is more likely to be implemented incorrectly: encrypt-then-MAC has several
places to get wrong: MAC-then-encrypt or encrypt-and-MAC (rather than encrypt-then-MAC)
order can reopen padding-oracle-style attacks; the MAC comparison must be constant-time to
avoid a timing oracle; padding itself must be handled carefully. AES-GCM collapses most of
that into a single library call, but concentrates all the risk into one rule: never reuse a
nonce. In distributed services, where many stateless instances encrypt independently under
a shared key, coordinating nonce uniqueness (a monotonic counter plus a per-instance ID, or
purely random 96-bit nonces) becomes the operational version of the same problem, and it is
what drives the key-rotation volume worked out below. A cipher with a larger nonce space,
like XChaCha20-Poly1305's 192-bit nonce, removes that
practical ceiling by making random-nonce collisions negligible even at very high message
volumes.
Worked example
Take NIST's rule of thumb that a random 96-bit nonce under one key should be retired once
roughly 2^32 messages have been encrypted. That 2^32 is NIST's deliberately conservative
invocation limit, chosen to keep the IV-collision probability down around 2^-32 to 2^-33; it
sits far below the true birthday bound of 2^48 (the square root of the 96-bit space, the point
where the chance of some collision reaches about 50 percent). 2^32 = 4,294,967,296. A service encrypting 10 million API payloads per day reaches
that count in 4,294,967,296 / 10,000,000 ≈ 429.5 days, a little over a year. That is a
concrete, calendar-relevant reason to build key rotation into the design up front rather than
treating AES-GCM as "safe forever" once it is wired up.
Trade-offs & pitfalls
- If you must support encrypt-then-MAC (say, for interoperability with an existing system),
the order matters: authenticate the ciphertext, not the plaintext, and use a
constant-time comparison when checking the tag. - "AEAD is simpler" does not mean "AEAD is foolproof"; it moves the single point of failure to
nonce management, which still requires real design attention in a distributed system.
Unlock Full Question Bank
Get access to all Cryptography Fundamentals interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.