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.
Design an auditable logging system that cryptographically protects integrity and ordering of logs across distributed microservices. Cover approaches such as HMAC chaining, append-only signing, periodic notarization, key management for signing keys, and verification after rotation or archive.
Sample Answer
Direct answer
Protect log integrity and ordering across distributed microservices by chaining each entry to the
one before it with a Hash-based Message Authentication Code (HMAC), so tampering with any past
entry breaks every chained value after it, and periodically "notarize" the chain's current tail by
signing it and publishing that signature somewhere the log owner cannot quietly rewrite. The
chaining detects local tampering cheaply; the periodic signed notarization is what prevents someone
who controls the whole log store from silently rewriting history and re-chaining it consistently.
Structured elaboration
- HMAC chaining. Each new entry Ei includes the previous entry's chain value:
maci=HMAC(K,maci−1∥Ei). Any modification, insertion, or
deletion changes every subsequent chain value, so a single, cheap symmetric operation per entry
detects tampering and reordering within a service's own log. - Cross-service ordering. A central collector assigns a monotonic global sequence number and
periodically computes a batch root (a Merkle-style aggregate hash over recent entries across
services), giving a single value that represents "everything up to this point, from every
service." - Periodic append-only signing and notarization. On a fixed schedule, an audited signing
service (backed by a Hardware Security Module, HSM) signs the current batch root and publishes it
to storage the log owner cannot rewrite after the fact (a write-once store, or an external
timestamping/transparency service). This is what upgrades "tamper-evident" into "tamper-evident
even against the log's own operator." - Key management and rotation. Use separate keys for per-entry HMAC chaining and for batch
signing, both managed through a Key Management Service (KMS) or HSM; rotate on a schedule with an
overlap window so entries signed near a rotation boundary can still be verified against whichever
key was actually current at that time.
Worked example
The tamper-evidence property is directly demonstrable, not just described:
import hmac, hashlib
key = bytes(range(32)) # per-epoch signing key, pinned for illustration
def chain(entries, key):
prev_mac = b"\x00" * 32
macs = []
for e in entries:
prev_mac = hmac.new(key, prev_mac + e.encode(), hashlib.sha256).digest()
macs.append(prev_mac)
return macs
def verify(entries, macs, key):
prev_mac = b"\x00" * 32
for i, (e, m) in enumerate(zip(entries, macs)):
expected = hmac.new(key, prev_mac + e.encode(), hashlib.sha256).digest()
if not hmac.compare_digest(expected, m):
return False, i
prev_mac = m
return True, None
log = ["login user=alice", "read file=report.csv", "delete file=report.csv"]
macs = chain(log, key)
print("untampered chain verifies:", verify(log, macs, key)[0])
tampered_log = list(log)
tampered_log[1] = "read file=payroll.csv"
ok, bad_index = verify(tampered_log, macs, key)
print("tampered chain verifies: ", ok, "| first entry that fails: index", bad_index)
reordered_log = [log[0], log[2], log[1]]
ok2, bad_index2 = verify(reordered_log, macs, key)
print("reordered chain verifies:", ok2, "| first entry that fails: index", bad_index2)
untampered chain verifies: True
tampered chain verifies: False | first entry that fails: index 1
reordered chain verifies: False | first entry that fails: index 1
Both an in-place rewrite and a simple reorder are caught at exactly the point they diverge from the
original chain, which is what lets an auditor pinpoint where tampering happened, not just that it
happened somewhere.
Trade-offs & pitfalls
- Verification after rotation. During a key-rotation overlap window, a verifier must know which
key was current for a given entry's timestamp; store key identifiers and validity intervals
alongside the notarization feed so old entries remain verifiable after the signing key retires. - Scalability. Per-entry HMAC chaining is cheap and can run at high volume; reserve the more
expensive asymmetric signature operation for periodic batch roots, not for every individual
entry. - What this design does and does not prevent. An attacker who compromises a service's current
signing key can still forge new forward entries until the key is rotated or revoked; periodic
notarization limits how much damage that window of compromise can do, since anything already
notarized before the compromise remains independently verifiable. - Common wrong turn: storing the chain and its notarization records in the same system with the
same access controls. If an attacker who can rewrite the logs can also rewrite the notarization
feed, the whole tamper-evidence property collapses; the notarization target must be genuinely
outside the log owner's own write access.
Suppose a memory disclosure vulnerability similar to Heartbleed was discovered in an SSL/TLS library used by your fleet. Describe how you would detect whether exploitation occurred, immediate mitigations, patch rollout strategy, and post-incident tasks such as key and certificate rotation, forensic evidence collection, and customer notification.
Sample Answer
Framing
Heartbleed (CVE-2014-0160, disclosed in 2014) is the canonical example of a memory disclosure vulnerability in a Transport Layer Security (TLS) library: a bug in OpenSSL's implementation of the TLS "heartbeat" extension let an unauthenticated remote attacker read chunks of the server process's memory, with no login required and, critically, often no trace in normal logs. The response to a Heartbleed-class bug in your own fleet has to assume the worst rather than wait for proof, because the nature of the bug makes proof unusually hard to get.
Why detection is unusually hard here
The underlying flaw: a heartbeat request includes a payload and a claimed payload length, but the vulnerable code trusted the claimed length without checking it against the payload actually sent, and echoed back that many bytes starting from the payload's location in memory, silently including whatever adjacent memory happened to be there. Since the length field is a 16-bit value, the maximum claimed length is 2^16 - 1 = 65,535 bytes, roughly 64 kilobytes of arbitrary process memory per request, and an attacker can repeat the request as many times as they like, each time potentially recovering a different memory window. Because a heartbeat exchange is a normal, expected part of TLS and the request itself doesn't look malformed at the protocol level, it produces no error and, under most default logging configurations, no log entry at all. Detection cannot rely on finding evidence of exploitation, its absence is not reassuring.
Detecting whether exploitation occurred
- Check the installed OpenSSL version against the known-vulnerable range (OpenSSL 1.0.1 through 1.0.1f were affected; 1.0.1g and later fixed it) across every server, load balancer, and embedded device in the fleet, including things people forget are running TLS termination (internal load balancers, management interfaces, third-party appliances).
- Search any available packet captures or intrusion-detection signatures for heartbeat requests with an anomalous claimed payload length relative to the actual payload sent, this is the one concrete artifact that can prove exploitation if you happen to have captured it, but its absence proves nothing given how rarely this traffic gets captured in practice.
- Treat any server that was running a vulnerable version and was reachable from the internet during the vulnerability window as a presumed compromise for planning purposes, even with zero direct evidence.
Immediate mitigations
- Patch OpenSSL to a fixed version on every affected system, prioritized by internet-facing exposure, and where an immediate patch isn't possible on a given system, disable the heartbeat extension as an interim compensating control if your TLS stack supports doing so.
- Take internet-facing vulnerable endpoints out of service or behind a patched proxy rather than leaving them exposed while a fleet-wide patch rolls out.
Patch rollout strategy
Patch by exposure, not by convenience: internet-facing systems first, then internal systems that terminate TLS for anything sensitive, then everything else. A patch alone does not undo prior exposure, so rollout speed matters less than what happens next.
Post-incident tasks
- Key and certificate rotation. Because the bug could leak a server's private key directly from memory, and there is no reliable way to prove it didn't, every private key that was ever loaded into a vulnerable process's memory should be treated as compromised: revoke the old certificates and reissue new ones with fresh keys, don't just reissue a certificate for the same key.
- Credential rotation. Session tokens, passwords, and any other secrets that could plausibly have passed through a vulnerable process's memory (anything handled during requests to that server in the exposure window) should be treated the same way, force credential resets rather than assuming they were untouched.
- Forensic evidence collection. Preserve whatever logs, packet captures, and system snapshots exist from the exposure window before they age out or get overwritten, even incomplete evidence is useful for later analysis and for any compliance or legal review of the incident.
- Customer notification. Because exploitation cannot be conclusively ruled out or confirmed from typical logging, notification and disclosure decisions should be made on the assumption of potential compromise, honestly communicating that certainty isn't available, rather than waiting for definitive proof that will likely never come.
Trade-offs and pitfalls
The single biggest mistake in a Heartbleed-class incident is treating "we found no evidence of exploitation" as equivalent to "we confirmed no exploitation occurred." Given how the bug works, those are not the same statement, and a post-mortem that conflates them tends to under-rotate keys and credentials, leaving a genuinely compromised key in service simply because nobody could prove it was used.
Provide a detailed analysis comparing RSA and elliptic curve cryptography (ECC) for large-scale TLS termination where millions of handshakes occur daily. Address CPU and memory cost per handshake, signature verification versus generation costs, key and certificate sizes, hardware acceleration impact, caching strategies, and long-term maintainability.
Sample Answer
Direct answer
Default to elliptic curve cryptography (ECC), specifically X25519 for key exchange and Ed25519 or
ECDSA over P-256 for signatures, for large-scale Transport Layer Security (TLS) termination. At
equivalent security strength ECC needs far smaller keys and signatures and a cheaper signing
operation than RSA, which is the operation that scales with handshake volume; keep RSA (2048 or
3072-bit) only as a compatibility fallback for legacy clients.
Structured elaboration
- Why signing cost dominates, not verification. In TLS 1.3 the server signs the handshake
transcript once per new connection (or resumes without a fresh signature at all), so signature
generation cost sits on the server's critical path at scale, while signature verification
happens on the client, one per connection, off the server's aggregate budget. - Key and signature sizes are exact, not estimated. An RSA-2048 modulus is 2048 bits, that is,
256 bytes, and an RSA signature is exactly that size. An ECDSA P-256 signature is two 256-bit
integers, 64 bytes raw (roughly 70 to 72 bytes once Distinguished Encoding Rules, DER, ASN.1
framing is added). An Ed25519 signature is a fixed 64 bytes. Every certificate in a chain carries
its issuer's signature, so this size difference compounds down the whole chain, which is why
ECDSA/Ed25519 certificate chains are noticeably smaller on the wire than RSA-2048 ones. - Hardware acceleration. AES-NI accelerates the symmetric bulk-data phase of TLS (the actual
application traffic), not the asymmetric handshake math, so it helps both algorithm choices
equally. Dedicated accelerators for modular exponentiation, such as Intel QuickAssist Technology
(QAT, a chipset feature that offloads public-key math to dedicated silicon), give RSA a much
bigger relative boost than ECC, precisely because RSA's operation is the more expensive one to
begin with; an EC-heavy fleet has less headroom left to reclaim from hardware. - Caching and session reuse. Use TLS 1.3 by default (it drops RSA key exchange entirely in
favor of ephemeral Diffie-Hellman), enable session resumption via session tickets or a
pre-shared key (PSK) to skip the full handshake on repeat connections, and use Online
Certificate Status Protocol (OCSP) stapling so clients do not each make a separate revocation
check.
Worked example
A rough, complexity-based estimate of why ECC signing is cheaper (not a timed benchmark, since
wall-clock numbers depend on hardware and library and are not reproducible from an answer): if you skip the arithmetic that follows, the single point is that RSA does its math on 2048-bit numbers while ECC does it on 256-bit ones, and because the cost of each multiplication grows with the square of that width, the far narrower ECC numbers are what make it cheaper. For the details: RSA-2048
with the Chinese Remainder Theorem (CRT) optimization (a standard speed-up that splits the RSA private-key computation into two half-size pieces, one per prime factor of the modulus, then recombines them) does its private-key operation as two
roughly 1024-bit modular exponentiations. A square-and-multiply exponentiation (the standard way to raise a number to a large power: read the exponent one bit at a time, squaring at every step and multiplying in the base only on the 1-bits) over a k-bit
exponent needs on the order of k modular squarings plus, on average, k/2 modular
multiplications, so per 1024-bit exponentiation that is roughly 1024+512=1536
multiplications of 1024-bit numbers, doubled for the two primes: about 3072 multiplications at
1024-bit width. An ECDSA P-256 signature needs one scalar multiplication of a 256-bit scalar (the elliptic-curve counterpart of exponentiation: repeatedly combining a fixed curve point with itself, once per bit of the scalar);
double-and-add (the point-by-point analogue of square-and-multiply) costs roughly 256 doublings plus, on average, 128 additions, about 384 point
operations, and each point operation (one add or double of curve points) costs on the order of 10 field multiplications (multiplications of the fixed-width numbers the curve is built over; one point add or double works out to roughly a dozen of them in the usual coordinate systems, so 10 is a round figure) at 256-bit
width, roughly 3840 multiplications at 256-bit width. Since schoolbook modular multiplication of a
k-bit number costs on the order of k2 bit operations (the grade-school method of multiplying every digit by every digit does about k×k single-bit steps for k-bit numbers), the total bit-operation counts come out
to roughly 3072×10242≈3.2×109 for RSA versus roughly
3840×2562≈2.5×108 for ECC, a difference of about an order of magnitude
(roughly 13x under these assumptions). Real libraries use faster multiplication and windowing
techniques that change the constants, not the qualitative conclusion: the much narrower modulus is
what makes elliptic-curve signing cheaper, and that gap only widens at higher RSA key sizes.
Trade-offs & pitfalls
- RSA public-key verification is actually cheap (the public exponent is conventionally 65537, a
17-bit value with few 1-bits), often cheaper than an EC verification, which needs a
double-scalar multiplication; this is why RSA can still look attractive for verify-heavy,
sign-light workloads, which server-side TLS termination is not. - Do not trust a generic multiplier like "ECC is N times faster" as a measured fact for your stack;
the real number depends on your library, curve, and hardware, and should be benchmarked on your
own production-shaped load rather than assumed. - Maintain algorithm agility (support more than one signature scheme in your TLS stack and be able
to swap without a client-facing break), since both RSA and ECC are broken by a sufficiently large
quantum computer; treat post-quantum migration as an awareness item to plan for, not a mechanism
to implement here. - Common wrong turn: benchmarking handshake cost while ignoring session resumption; a design that
looks expensive per-handshake can be cheap in aggregate if most connections resume instead of
performing a full handshake.
Discuss the operational concerns when choosing randomness sources in cloud VMs, containers, and hardware. Explain entropy starvation, how to bootstrap entropy on new instances, and practical mitigations (e.g., rngd, getrandom/URANDOM behavior, provisioning entropy via cloud agent or HSM).
Sample Answer
Direct answer
Entropy starvation happens when a freshly booted virtual machine (VM), container, or device has not
yet gathered enough unpredictable input to safely seed its cryptographically secure pseudorandom
number generator (CSPRNG), which is the source every key, nonce, and token generation call relies
on. Cloud and container environments make this worse than physical hardware because a VM can be
cloned or restored from a snapshot with an already-seeded-looking generator that is, in fact,
identical to another instance's; the fix is to feed real, instance-unique entropy in early rather
than trust the guest kernel's default boot-time sources alone.
Structured elaboration
- How the kernel behaves. On Linux, the
getrandom()system call blocks (or, with a
non-blocking flag, returns an error) until the kernel's internal CSPRNG has been seeded once
after boot;/dev/urandomis meant to behave the same way on modern kernels, but on VM images
built from older kernels or minimal boot paths, that seeding event can be slow if the only inputs
are interrupt timing jitter that a virtualized, otherwise-quiet guest does not generate much of. - Why cloning is the cloud-specific risk. A snapshot or cloned image can, in the worst case,
carry over CSPRNG state from before the clone, so two "freshly booted" instances derived from the
same image can end up seeded almost identically. This is not hypothetical: a widely cited 2012
academic study (Heninger, Durumeric, Wustrow, and Halderman, "Mining Your Ps and Qs") found a
meaningful population of RSA and DSA keys generated on freshly booted embedded Linux devices that
shared factors, traced back to exactly this kind of boot-time entropy shortfall. - Sources available. A hardware random number generator, either a physical Trusted Platform
Module (TPM)/secure element or a paravirtualizedvirtio-rngdevice that channels the host's
hardware entropy into the guest, is the strongest available source in a VM;rngd(a user-space
daemon that feeds a hardware source into the kernel's pool) is the standard way to wire it up.
Worked example
Picture a fleet auto-scaling event: 200 new VM instances boot from the same golden image within a
few seconds of each other. If that image's kernel has no virtio-rng attached and relies solely on
interrupt-timing jitter to seed its CSPRNG, every one of those 200 instances is drawing from the
same class of low-diversity, low-volume noise source at nearly the same wall-clock moment, which is
exactly the "identically seeded clones" risk the 2012 study above found in the wild, just produced
by autoscaling instead of manual imaging. Attaching virtio-rng to the image and running rngd
against it before any cryptographic material is generated removes the shared bottleneck: each
instance now draws from the host hypervisor's own hardware entropy source, which is independent
per host and not tied to how many guest VMs happen to boot in the same second.
Trade-offs & pitfalls
- Bootstrap mitigation. Attach
virtio-rng(or equivalent) to every VM image rather than
relying on interrupt jitter alone; runrngdagainst it; have cloud-init or an equivalent
provisioning agent inject additional per-instance-unique material (instance ID, a fresh
provider-supplied random value fetched over an authenticated channel) mixed into the pool as a
supplement, never as a replacement for real entropy. - Delay, don't fake it. If a service must generate a long-term key at first boot, gate that
generation on confirmation that the kernel's CSPRNG has actually been seeded, rather than
falling back to a weaker, always-available source "so boot doesn't hang." A slow, correct key
beats a fast, predictable one. - Containers usually share the host kernel's entropy pool, so a container does not need its own
hardware RNG in most deployments, but a container started from a frozen, long-cached image on a
host that has not yet accumulated entropy inherits the same startup risk as a VM. - Monitoring. Alert on unusually long blocking on cryptographic syscalls at boot and on
entropy-pool health metrics where the kernel exposes them; a fleet-wide pattern of slow key
generation at scale-out time is a real operational signal, not noise.
Unlock Full Question Bank
Get access to all 8 Cryptography Fundamentals interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.