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.
Your SIEM shows repeated TLS handshake failures to an internal service after a certificate rotation. Failures indicate 'bad_certificate' from several clients. Explain your investigation steps: what logs and systems you inspect, how to verify certificate chain and private key correctness, and quick mitigations to restore service while preserving forensic data.
Sample Answer
Framing
A bad_certificate alert is Transport Layer Security's (TLS) way of saying the client rejected something specific about the certificate the server presented during the handshake, it is a symptom, not a diagnosis. Given that this started right after a certificate rotation, the investigation should assume the rotation itself introduced the problem until proven otherwise, and the response needs to restore service without destroying the evidence needed to confirm what actually broke.
Investigation steps
- Confirm the timeline. Check when the failures started against the exact deployment time of the certificate rotation across your fleet, a rollout that wasn't atomic (some nodes updated, some not) often shows up as intermittent failures rather than a hard outage, which is itself a diagnostic clue.
- Inspect what's actually being served. Connect directly to an affected node's Transport Layer Security endpoint and retrieve the certificate chain it presents (most TLS tooling can dump the full chain, not just the leaf). Compare it against what you intended to deploy: is the leaf certificate the new one? Is the full intermediate chain present, or did the rotation deploy the new leaf certificate without updating the intermediate bundle, a very common rotation mistake?
- Verify the certificate and private key actually match. A rotation that swaps a certificate file but not its paired private key (or vice versa) produces exactly this kind of failure. Compute a fingerprint of the public key embedded in the certificate and compare it against a fingerprint of the public key derived from the private key file on disk, if they don't match, the server is presenting a certificate for a key it doesn't actually hold, and the handshake will fail every time.
- Check certificate validity and identity fields. Confirm the new certificate's validity window has actually started (a certificate rotated slightly early, before its
notBeforedate, would be rejected), and confirm its Subject Alternative Name entries match the hostnames clients are actually connecting to, a rotation that regenerated a certificate with the wrong hostname list is a common human error. - Check trust store propagation on the client side. If the rotation introduced a new intermediate certificate authority or changed the root, clients (or upstream proxies, load balancers, or internal services) that haven't been updated with the new trust chain will reject the new certificate as untrusted even though the server side is configured correctly, this shows up specifically as failures from some clients, not others.
- Correlate logs across layers. Server-side TLS termination logs, load balancer or reverse proxy logs, and client-side error logs each show a different part of the picture, the exact alert reason and which specific check failed is usually visible in at least one of these, don't stop at the first log source that mentions
bad_certificate.
Quick mitigations that preserve forensic data
- Roll back to the previous, known-good certificate and key pair on affected nodes to restore service immediately, but copy the failing certificate, key, and relevant logs to a separate location before overwriting them on the live nodes, don't let a rollback destroy the only evidence of what went wrong.
- If a full rollback isn't immediately possible everywhere, route traffic away from affected nodes (via load balancer health checks or manual removal from the pool) rather than restarting services repeatedly, repeated restarts can overwrite log buffers and make root-causing harder.
- Avoid regenerating a "fixed" certificate in a hurry before you've confirmed exactly what was wrong with the previous one, a rushed second rotation risks introducing a second, different mistake on top of the first.
Trade-offs and pitfalls
The single most common root cause behind this exact symptom is an incomplete rollout, a certificate and its matching intermediate bundle deployed to some nodes but not others, or a private key file that didn't get updated in lockstep with its certificate. Treat certificate rotation as an atomic, verifiable deployment (verify the live chain and key match on every node before declaring the rotation complete) rather than a file copy, since the failure here is silent until a client actually tries to validate the result.
Outline an approach to formally test whether an application's use of cryptography is correct: include test cases for IV/nonce uniqueness, key lifecycle (generation/storage/rotation), authenticated encryption verification, and integration tests to ensure correct protocol flows (e.g., TLS handshake). What automated checks would you include in CI/CD?
Sample Answer
Direct answer
Test an application's cryptographic correctness the same way you'd test any other correctness property: unit tests for the specific invariants that, if violated, break security silently (nonce uniqueness, key-lifecycle transitions, authenticated-decryption failure), plus integration tests that exercise the real protocol flow end to end, and wire both into the pipeline so a regression is caught before it ships rather than discovered in an incident review.
IV/nonce uniqueness
A nonce that repeats under the same key breaks confidentiality (stream ciphers and CTR/GCM modes) or worse. Test the actual nonce-generation logic in isolation, at scale, not just "does encryption succeed."
Key lifecycle
Test generation (keys come from the intended CSPRNG, cryptographically secure pseudorandom number generator, path, not a stubbed or seeded one), storage (a key never appears in plaintext in logs or a debug dump; in tests this becomes asserting the key-management mock was called for encrypt/decrypt rather than a raw key object being serialized), and rotation (generate key v1, encrypt data, rotate to v2, confirm v1-encrypted data still decrypts until re-encrypted, and confirm new writes use v2).
Authenticated-encryption verification
Confirm the system fails closed: a single flipped ciphertext bit must be rejected outright, not silently accepted or partially decrypted.
Worked example
import os
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
from cryptography.exceptions import InvalidTag
def test_nonce_uniqueness_under_counter_scheme(num_messages=10_000):
seen = set()
for counter in range(num_messages):
nonce = counter.to_bytes(12, "big")
assert nonce not in seen, f"nonce reused at counter={counter}"
seen.add(nonce)
print(f"nonce uniqueness OK across {num_messages} messages")
def test_tamper_detection_fails_closed():
key = AESGCM.generate_key(bit_length=256)
aesgcm = AESGCM(key)
nonce = os.urandom(12)
plaintext = b"transfer:amount=100;to=acct-42"
ct = aesgcm.encrypt(nonce, plaintext, associated_data=b"v1")
tampered = bytearray(ct)
tampered[0] ^= 0x01
try:
aesgcm.decrypt(nonce, bytes(tampered), associated_data=b"v1")
raise AssertionError("tampered ciphertext was accepted")
except InvalidTag:
print("tamper detection OK: modified ciphertext was rejected")
recovered = aesgcm.decrypt(nonce, ct, associated_data=b"v1")
assert recovered == plaintext
print("legitimate ciphertext still decrypts correctly")
test_nonce_uniqueness_under_counter_scheme()
test_tamper_detection_fails_closed()
Output:
nonce uniqueness OK across 10000 messages
tamper detection OK: modified ciphertext was rejected
legitimate ciphertext still decrypts correctly
Integration tests for protocol flows
For something like a TLS handshake, a unit test on the crypto primitives in isolation cannot catch a misconfiguration in how they're assembled into a live connection. An integration test should connect to the real (or a long-lived staging) endpoint and assert on the outcome: the negotiated protocol version is at least the intended minimum, the negotiated cipher suite is from an explicit allow-list, the certificate chain validates, and, critically, a client that offers only deprecated protocol versions is refused rather than silently downgraded.
Automated checks for CI/CD (continuous integration and delivery pipeline)
- Run a known-answer test-vector suite (NIST CAVP-style vectors, the RFC 5869 HKDF vectors, Project Wycheproof) on every pull request that touches crypto code.
- Run a dependency and CVE scan against the pinned crypto library version.
- Add a lightweight, time-boxed fuzz pass over ciphertext-parsing and padding-validation code on every build, with a longer nightly run.
- Add a review checklist (or a best-effort static check) flagging manual
==/!=comparisons against anything named like a secret, HMAC, or token, requiring a constant-time comparison function instead. - Run the live-endpoint handshake canary above on a schedule, not just at deploy time, so a certificate rotation or a config drift that reintroduces a deprecated protocol is caught within hours, not at the next incident.
Trade-offs and pitfalls
Unit tests on invariants like nonce uniqueness are fast and deterministic, but they test the code's logic, not the deployed configuration, only the live-endpoint integration test catches a case where the code is correct but the server config allows a weak cipher suite anyway. Conversely, integration tests against a real endpoint are slower and environment-dependent, so keep the fast unit-level invariant tests on every commit and reserve the live-endpoint canary for a scheduled or pre-deploy run rather than every commit.
Define initialization vector (IV) and nonce as used in block/stream cipher modes. What properties must each satisfy (randomness vs uniqueness), and what happens in practice if a nonce is reused with a mode like GCM?
Sample Answer
Direct answer
An initialization vector (IV) or nonce ("number used once") is extra, non-secret input
combined with the key so that encrypting the same plaintext twice under the same key does not
produce the same ciphertext twice. Different cipher modes need different properties from it:
some need it unpredictable, all of them need it to never repeat under the same key. Reusing a
nonce with GCM is not a minor bug, it is a full break of that key's confidentiality and
authenticity.
Structured elaboration
- CBC mode: the IV should be unpredictable (ideally generated by a CSPRNG) and must never
repeat under the same key. It does not need to be secret, it is normally sent alongside the
ciphertext. - CTR and GCM modes: the nonce's essential property is uniqueness per key, not secrecy or
even unpredictability. GCM's internal encryption is CTR-mode-like: the nonce plus a
block counter generates a "keystream" that gets XORed with the plaintext. - Why nonce reuse under GCM is catastrophic: if the same key and nonce encrypt two
different messages, both use the identical keystream. XORing the two ciphertexts together
cancels the keystream out entirely, leaving the XOR of the two plaintexts, a classic
"two-time pad" break: an attacker who knows or guesses one plaintext immediately recovers
the other. GCM reuse is worse still: it can also expose the authentication subkey, letting
an attacker forge arbitrary valid messages for that key going forward.
Worked example
Say a reused keystream (from encrypting two different messages under the same key and nonce)
happens to be the bytes A5 3C 91 77. Encrypting "HELP" (48 45 4C 50 in hex) with it gives
ciphertext C1 = 48^A5, 45^3C, 4C^91, 50^77 = ED 79 DD 27. Encrypting "RUN!" (52 55 4E 21)
with the same keystream gives C2 = 52^A5, 55^3C, 4E^91, 21^77 = F7 69 DF 56. Now XOR the
two ciphertexts: C1 xor C2 = ED^F7, 79^69, DD^DF, 27^56 = 1A 10 02 71. That is exactly
"HELP" xor "RUN!" (48^52, 45^55, 4C^4E, 50^21 = 1A 10 02 71), with the keystream fully
canceled out. If an attacker already knows or can guess one plaintext ("HELP"), they recover
the other directly: M2 = M1 xor (C1 xor C2) = 48^1A, 45^10, 4C^02, 50^71 = 52 55 4E 21, which
decodes back to "RUN!". No key was ever recovered, and none was needed.
Trade-offs & pitfalls
- "Random" is a stronger property than "unique," but for GCM specifically, uniqueness is the
requirement that must never be violated; a random-but-short (96-bit) nonce chosen fresh
every time is standard practice precisely because random values are very unlikely to
collide at reasonable message volumes, not because randomness itself is the requirement. - A common real mistake is initializing a nonce counter to zero on every server restart or
every new connection, silently creating repeats across restarts or connections that share a
key.
Explain the roles of salting and key stretching in password-based key derivation and storage. Describe how salts should be generated and stored, why unique salts prevent precomputation/rainbow-table attacks, and how key stretching (iterative hashing, memory-hard functions) increases attacker work. Illustrate with concrete examples of attacks that salting and stretching mitigate and note any remaining risks that require additional controls.
Sample Answer
Direct answer
Salting adds a random, unique-per-user value to a password before hashing so that identical
passwords never produce identical stored hashes; key stretching deliberately makes each
hashing attempt slow (or memory-hungry) so an attacker who steals the hash dump still has to
pay a real per-guess cost. Together they turn "crack the whole database at once with a
precomputed table" into "crack each password individually, slowly."
Structured elaboration
- Generating and storing salts: generate a fresh, random salt (commonly 16 bytes) from a
CSPRNG per user, and store it alongside the hash. The salt is not secret, it can sit in
plaintext in the same database row; its job is uniqueness, not confidentiality. - Why unique salts defeat precomputation: a rainbow table (a precomputed map from common
passwords to their hashes) is only useful because it lets an attacker look up a hash instead
of computing one. A unique salt per user means the same password produces a different hash
for every user, so an attacker would need a separate precomputed table per salt value, which
is infeasible at any real user-base size. - How key stretching increases attacker work: an iterated hash (many rounds of a hash
function) or a memory-hard function (Argon2id, scrypt) makes each individual guess
expensive in CPU time, memory, or both. This does not slow down a legitimate login (one
verification per attempt is cheap in absolute terms) but multiplies the cost of trying
billions of candidate passwords offline by the same factor.
Worked example
Suppose 5,000 users in a leaked database chose the password "password123". With a plain,
unsalted hash, all 5,000 rows show the identical hash value, so cracking it once (via a
rainbow table lookup or a single guess) reveals all 5,000 accounts simultaneously. With unique
per-user salts, those same 5,000 users produce 5,000 different hash values, and an attacker
must run the guess-and-check process separately against each one; a rainbow table built for
the unsalted case is useless here since it was never built for any of these specific salts.
Trade-offs & pitfalls (remaining risks needing additional controls)
- Salting and stretching only make offline cracking (against a stolen hash) expensive; they
do nothing against online guessing at the login endpoint, which still needs rate limiting
and account lockout/backoff. - A short or common password remains crackable even when properly salted and stretched,
because the search space itself is small; this is why NIST SP 800-63B and similar guidance
push for password length and breach-list checking rather than relying on hashing alone. - Choosing stretching parameters too low (to save server CPU) narrows the gap between "safe"
and "fast enough to crack anyway"; parameters need periodic revisiting as hardware gets
cheaper.
You're reviewing a colleague's pull request that adds encryption for a new feature. Walk through what you'd look for during review, and for each issue you flag, explain why it's a problem and how you'd fix it.
Sample Answer
Direct answer
A crypto-focused code review is really a checklist walk: where does the randomness come from,
where do keys live, which algorithm and mode was picked, how is the IV/nonce generated, is
there an integrity check on top of confidentiality, and does error handling leak anything
useful to an attacker. Most real-world crypto bugs live in these plumbing decisions, not in
the mathematics of the algorithm itself.
Structured elaboration
- Randomness source. Is the key, IV, or nonce generated from a CSPRNG (the platform's
cryptographic random source), or from a general-purposerandom()/Math.random()-style
function? The latter is predictable and unsafe for any of these values; flag it and replace
it with the platform's cryptographic RNG API. - Key handling. Is the key hardcoded in source, a config file, or a constant, versus
pulled from a secrets manager or KMS (key management service) at runtime? A hardcoded key
means anyone with source access (or a leaked repo) has the key forever, and rotating it
requires a code deploy. Fix: load it from a secrets store, never commit it. - Algorithm and mode choice. Is the cipher mode ECB (Electronic Codebook)? ECB encrypts
identical plaintext blocks to identical ciphertext blocks, visibly leaking structure (the
classic demonstration is an ECB-encrypted image where the outline is still recognizable).
Flag any ECB usage and replace it with an AEAD mode like AES-GCM. - IV/nonce handling. Is a fresh IV/nonce generated per encryption, or is one hardcoded or
reused across calls? A repeated IV under CBC leaks structure; a repeated nonce under GCM is
a full break of that key (see the nonce-reuse mechanics above). Fix: generate fresh
per-message values from a CSPRNG and store them alongside the ciphertext. - Integrity, not just confidentiality. Does the code use a plain cipher with no
authentication at all? Encryption without an integrity check lets an attacker tamper with
ciphertext undetected. Fix: use an AEAD cipher, or add a properly-ordered encrypt-then-MAC
if the library does not offer AEAD. - Library maturity and API usage. Is this a hand-rolled implementation of a
well-known primitive, or a vetted library used through its high-level, misuse-resistant API?
Flag any custom crypto code; recommend a maintained library instead. - Error handling. Do error messages or timing distinguish "wrong key" from "wrong padding"
from "tampered ciphertext"? Distinguishable errors can become an oracle an attacker probes
repeatedly to recover plaintext without ever learning the key. Fix: return one generic
failure for all decryption errors, and use constant-time comparison for any secret-derived
values.
Worked example
A pull request adds AES.new(key, AES.MODE_ECB) with key = b"my-static-key-1234567890123456"
hardcoded at the top of the file, and no separate authentication step. The review comment
would name three separate, stackable problems: (1) ECB leaks plaintext structure regardless of
key strength, switch to AES.MODE_GCM; (2) the key is a literal in source, move it to the
secrets manager the rest of the service already uses; (3) there is no authentication tag at
all, so tampered ciphertext decrypts silently, which GCM's tag would catch for free once
adopted.
Trade-offs & pitfalls
- Not every review will find all of these at once; the discipline is running the same
checklist every time rather than pattern-matching on whatever looks unusual first. - A review that only checks "is the algorithm modern" and stops there misses the majority of
real crypto bugs, which live in key handling, IV/nonce handling, and error behavior, not
algorithm choice.
Unlock Full Question Bank
Get access to all 41 Cryptography Fundamentals interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.