Applied Cryptography and Key Management Questions
Selecting and applying cryptographic primitives correctly: symmetric and asymmetric encryption, hashing, digital signatures, key derivation, secure random number generation, and public key infrastructure. Covers key lifecycle management, key exchange and distribution, choosing appropriate algorithms for a given constraint set including resource-constrained environments, and the forward-looking side of algorithm lifecycle: cryptographic agility and algorithm-migration strategy, forward secrecy, and the post-quantum cryptography transition and planning upgrades without breaking existing data or interoperability. The applied-crypto engineering layer, distinct from compliance-driven crypto standards.
Design telemetry, metrics, and alerting to detect and respond to cryptographic failures: certificate expiry, OCSP-stapling failures, TLS handshake degradation, KMS latency/failures, and anomalous key usage (like an unusual signing rate). Define the SLOs, the actual metric names (counters/gauges/histograms) you'd emit, alert thresholds, and a simple operator playbook for each.
Sample Answer
Direct answer: Build telemetry around each distinct crypto failure mode with the right metric shape for what it measures: a counter for events that only accumulate (like a failure count), a gauge for a value that moves up and down (like days remaining before an expiry), and a histogram for a distribution you need percentiles from (like handshake latency). Define an internal reliability target (a service-level objective, or SLO) and a short, first-action playbook for each failure mode, and group alerts by failure mode so an on-call engineer is never woken by five different alerts describing the same underlying problem.
| Failure mode | Metric (name and type) | Illustrative SLO/threshold | First playbook action |
|---|---|---|---|
| Certificate expiry | cert_days_until_expiry (gauge, per hostname) | warn at 30 days remaining, page at 1 day (an organization-tunable convention, not a universal standard) | Confirm the renewal automation (ACME client or internal CA workflow) actually ran and check its last-success timestamp; if broken, renew manually now and fix the automation before the next cycle |
| OCSP-stapling failures | ocsp_staple_fetch_failures_total (counter) and ocsp_staple_age_seconds (gauge) | failures stay rare (single digits per day), staple age refreshed well before the response's own validity window elapses | OCSP (Online Certificate Status Protocol) stapling means the server attaches a recent, signed proof that its certificate is not revoked (a staple) to the TLS handshake, so each client does not have to contact the certificate authority itself. Check connectivity from the TLS terminator to the certificate authority's OCSP responder; if the responder itself is down, most clients tolerate a soft-fail (they proceed with the connection rather than rejecting it when that proof is missing), so the immediate risk is degraded revocation-checking assurance, not necessarily an outage, but track it and keep serving the last known-good staple |
| TLS handshake degradation | tls_handshake_duration_seconds (histogram) and tls_handshake_failures_total (counter, labeled by failure reason) | p99 handshake latency within an agreed budget; failure rate below a small fixed ceiling | Check the failure-reason label distribution first: a spike concentrated in one alert type points to a specific root cause (an expired or mismatched certificate), while a broad, unlabeled spike points to resource exhaustion or a downstream key management service (KMS) dependency issue |
| KMS latency or failures | kms_operation_duration_seconds (histogram, per operation type) and kms_operation_errors_total (counter, labeled by error type) | call latency stays a defined fraction of the overall request budget; throttling-type errors trend toward zero | Distinguish throttling (your own request rate exceeded a quota, fix with client-side backoff) from a genuine service outage (check the provider's status page) from access-denied (a permissions regression, likely from a recent deploy); each has a different owner and fix |
| Anomalous key usage (unusual signing rate) | key_usage_operations_total (counter, labeled by key ID and operation) | alert if a key's rate sustains well above its own historical baseline for that hour of week (illustrative convention: 3x) | Treat this as a potential security incident, not a performance issue: identify what is calling the key, check whether the spike matches an expected traffic change, and be ready to revoke or rotate the key's access if it cannot be quickly explained |
Worked example. For the anomalous-key-usage threshold: if a signing key's normal weekday hourly volume is 500 operations, an illustrative 3x threshold fires once sustained volume crosses:
500 operations/hour x 3 = 1,500 operations/hour
That number is directly derived from whatever baseline your own telemetry establishes for that specific key, not a fixed industry figure; recompute it per key rather than hard-coding one global threshold.
Trade-offs and pitfalls. Alert fatigue is the largest risk with a list this size: five failure modes can easily explode into twenty-plus individual alerts if you are not careful, so group by failure mode as done above rather than by raw metric, and make sure every alert's playbook fits in the "first action" an on-call engineer needs, not the full incident response. The metric names above follow common counter and gauge naming conventions (_total for counters, _seconds for time-based histograms) but are illustrative, not any single vendor's mandated schema; adapt them to whatever naming convention your organization's telemetry system already standardizes on rather than inventing a new one just for cryptographic metrics.
Design an audit-logging architecture for all key-management operations (create, use, rotate, export, delete) that meets compliance expectations and enables detection of anomalous behavior, without leaking key material into the logs themselves. Define the event types and mandatory fields, your redaction/hashing strategy for sensitive fields, retention and access controls, log integrity protections (tamper-evident or append-only, HSM-signed), and how this feeds a SIEM.
Sample Answer
Direct answer
Log the operation and its context, never the key material or anything that could reconstruct it: every event carries a principal, a key identifier and version, never the key itself, the action, the result, and enough request context to answer who touched what, from where, with what outcome. Make the log tamper-evident, append-only and cryptographically chained or HSM-signed, and route it into a SIEM with baseline-deviation rules, since catching a compromised credential misusing a key is mostly a question of whether behavior looks unusual for that specific principal and that specific key.
Structured elaboration
Event types and mandatory fields
- Event types: KeyCreated, KeyUsed tagged by operation (Encrypt, Decrypt, Sign, Verify, Wrap, Unwrap), KeyRotated, KeyExported, KeyArchived, KeyDeletionScheduled and KeyDeleted, PolicyChanged, and AccessDenied.
- Mandatory fields on every event: timestamp from a synchronized clock, principal identity and how it authenticated, source network or service identity, key identifier and version, the operation attempted, request context (which resource the operation was protecting, where known), result with a coarse reason, and a correlation ID tying the event to the calling application's own trace.
Redaction and hashing strategy
- Never log plaintext key material, DEKs, wrapped-key ciphertext bytes, or the plaintext or ciphertext of the data being protected.
- Log the key ID and version, a stable, non-secret handle, instead. Where you need to detect duplicate or reused metadata without exposing the key, hash the metadata itself, never the key material, since a high-entropy key doesn't need protecting by hashing and there is no reason to have logged it in the first place.
- Truncate, tokenize, or hash any privacy-sensitive request context (a customer identifier, a document name) per the org's existing log-classification rules, key-management logs are not exempt from those rules just because their primary purpose is security.
Retention and access controls
- Retain for the strictest applicable requirement, commonly a year or more for key-management events specifically, since an investigation into a compromise discovered late needs history that predates discovery.
- Access to the log store is a separate, narrower permission from access to the KMS itself: an auditor can read logs with no operational KMS permission, and a key-admin cannot modify or delete log entries, ever, that separation is what makes the log trustworthy as evidence rather than something the person under investigation could have edited.
Log integrity protections
- Append-only storage, write-once or a storage class that structurally disallows overwrite or delete within the retention window, so a compromised admin credential can't cover its tracks by editing history.
- Tamper evidence via hash-chaining, each entry carries the hash of the previous one so any retroactive edit breaks the chain, or HSM-signed batches of entries, giving a cryptographic guarantee of integrity, not just an access-control one.
- Ship logs to a destination outside the blast radius of the systems being audited, a separate account or administrative domain, so compromising the KMS's own infrastructure doesn't also compromise the record of what happened on it.
Feeding a SIEM and detecting anomalous behavior
- Stream every event, not a sampled subset, to the SIEM in near real time; sensitive-operation logs are exactly the low-volume, high-value signal where sampling would silently throw away the one event that mattered.
- Alert specifically on: a key-admin or backup-operator credential performing an actual decrypt or sign operation, which should structurally never happen if role separation is enforced, so its mere occurrence is a red flag regardless of intent; a sudden volume spike in decrypt or export operations from a single principal or an unfamiliar source network; a burst of access-denied events followed by a success, a classic credential-guessing or privilege-escalation pattern; unusually high key usage immediately preceding a scheduled deletion; and access from a geography or network segment that principal has never used before.
- Baseline these per principal and per key, not globally, since normal decrypt volume for a high-traffic service and a rarely-used administrative key are wildly different, and a single global threshold either misses real anomalies or drowns the SIEM in false positives.
Worked example
If a service principal's decrypt calls for a specific key have averaged 500 an hour over the trailing 30 days, an hour with 5,000 calls from that same principal against the same key, ten times its own established baseline, especially if paired with an unfamiliar source network, is exactly the kind of signal that should page someone. The trigger isn't that 5,000 calls an hour is inherently suspicious in isolation, it's that it is a tenfold deviation from that specific principal's own pattern.
Trade-offs and pitfalls
Common wrong turn: logging the wrapped key ciphertext just in case it's useful for debugging, which expands the log store's own blast radius for no operational benefit, since a wrapped key that later needs debugging can be re-fetched from the KMS by an authorized principal instead. Common wrong turn: a single global anomaly threshold across all principals and keys, which either misses a genuine deviation for a low-volume key or generates so many false positives on a high-volume one that the alert gets tuned out. Senior signal: designing what is not logged, the redaction list, with the same rigor as what is logged, an architecture that only thinks about coverage and never about leakage tends to eventually log the thing it was built to protect.
You're asked to lead a company-wide 'key compromise drill.' Outline the plan: objectives, participants across engineering, security ops, legal, and communications, the simulated compromise scenarios, a step-by-step playbook, decision gates, reporting/metrics, and the post-drill remediation actions.
Sample Answer
Direct answer
Run a key-compromise drill like any well-designed incident exercise: pick a specific, realistic
compromise scenario in advance rather than a vague "something bad happened to a key," involve every
function that would actually be paged in a real incident, not only engineering, script explicit
decision gates so the drill tests decision-making under time pressure and not just running a rotation
script, and track every gap found to closure so the next drill does not rediscover the same problems.
Structured elaboration
- Objectives. Validate that the actual key-rotation and revocation runbooks work end to end, not
just that they exist on paper. Measure realistic time-to-detect and time-to-contain. Surface
cross-team coordination gaps, who needs to approve what, and in what order. Build muscle memory so a
real incident is not the first time anyone has run the playbook. - Participants. Engineering or platform (executes the technical rotation or revocation), security
operations (leads the incident and makes containment calls), legal (advises on breach-notification
obligations and how a legal hold might interact with any planned key destruction), communications
(drafts internal, and if warranted, external or customer messaging), and an incident commander or
executive sponsor who can actually authorize a costly containment action, such as taking a service
offline, without waiting on a chain of approvals mid-drill. - Simulated compromise scenarios. Pick two or three specific, realistic scenarios rather than one
vague one, for example: a departing engineer's credentials with Key Management Service (KMS) admin
access are found reused after termination; a code-signing key appears in a public source-code
repository; an anomalous volume of decrypt calls is detected on a customer-data key. Specificity
matters because the actual containment steps genuinely differ by scenario: a leaked signing key needs
revocation, re-signing, and customer notification about affected artifacts, while internal credential
misuse needs an access review and rotation, not necessarily external notification. - Step-by-step playbook. Detect and confirm, then formally declare (open the incident and assign an
incident commander), then contain (revoke or rotate the specific compromised key, not a reflexive
"rotate everything" that can cause its own outage), then assess blast radius (what was actually
encrypted or signed with the compromised key, and during what window), then notify (internal
stakeholders first, then legal-directed external notification if the assessed impact requires it),
then remediate (fix the root cause, for example how the credential leaked), then recover (confirm
normal operations resumed), then review (a post-mortem). - Decision gates. Script explicit go or no-go points where the incident commander must make a real
call with the information available at that moment, for example: rotate a production signing key
right now and accept a deployment freeze, or wait two hours for a lower-risk window. Testing whether
the right people can make the right call under genuine uncertainty is the actual point of a drill, not
watching engineers execute a script. - Reporting and metrics. Time from simulated detection to declared incident, time from declaration
to containment, and the number of manual or undocumented steps discovered, each one is a real runbook
gap. After the drill, track the number of remediation items opened and their time to close. - Post-drill remediation. Every gap found becomes a tracked action item with an owner and a
deadline, and the next drill should specifically re-test whether the previous drill's gaps were
actually fixed, otherwise drills become an exercise in rediscovering the same gaps every time.
Worked example
Scenario chosen: a contractor's laptop with a locally cached KMS access token is reported stolen. At
minute 15 of the simulated timeline, a decision gate forces the incident commander to choose: revoke
the token immediately, risking disruption to a nightly batch job that contractor's automation runs, or
wait for confirmation the laptop is actually compromised, risking a wider window of potential misuse.
The drill enforces a time limit on that decision to model real urgency, then reveals the "ground
truth" afterward, in this design, the laptop genuinely was stolen, so the after-action review can
discuss whether the decision-making PROCESS was sound, not only whether the outcome happened to be
correct.
Trade-offs & pitfalls
- A drill that only exercises engineers running a script, and never the legal, communications, and
decision-authority chain, misses most of what actually goes wrong in a real incident: real incidents
are usually messier because of coordination and decision gaps, not because nobody knew the right
command to run. - A scenario so vague it forces no concrete decisions produces a low-value drill; specificity is what
makes the exercise useful. - Skipping the tracked-remediation step turns drills into a compliance checkbox rather than an actual
improvement loop.
Your cloud KMS provider discloses a critical vulnerability and you must migrate keys and re-encrypt data across cloud providers quickly. Outline an expedited, secure migration plan that preserves confidentiality during transfer, minimizes downtime, remaps access controls to the new provider, and gives you full auditability of the migration. How does the plan change if instead the trigger is a KMS service principal being exfiltrated from CI and used to decrypt sensitive objects, or a vault's master key being suspected extracted: what would you freeze first, and what cross-team responsibilities and regulatory notifications kick in?
Sample Answer
Direct answer: These are two different triggers sharing one underlying mechanism, and they demand two different postures. A disclosed key management service (KMS) vulnerability, not yet exploited against you, lets you migrate on your own timeline within an expedited but planned window. A suspected credential exfiltration or master-key extraction is an active-compromise incident that demands an immediate freeze, then forensics, then migration, because an attacker may already be reading your data right now: every hour spent "migrating carefully" is an hour of continued exposure.
Part A: migrating after a disclosed vendor vulnerability
- Preserve confidentiality during transfer. Never move plaintext data between providers over the wire. Keep the data in place, or move ciphertext only, and instead re-wrap the per-object data-encryption keys: unwrap under the old (vulnerable-vendor) key, immediately re-wrap under a new key in the destination provider, and never persist the intermediate plaintext key to disk or logs, in memory only, for the shortest possible window, cleared using proper memory-hygiene practices.
- Minimize downtime. Dual-read during the transition (reads try the new provider's key first, fall back to the old one), single-write immediately (new writes cut over to the new provider right away, since you do not want any new data protected by a key you no longer trust).
- Remap access controls, from scratch, not by copying. This is the moment to re-derive least privilege rather than performing a one-to-one permission copy: IAM policy languages, principal types, and default-deny postures differ meaningfully across cloud providers, and a naive direct copy risks either breaking legitimate access or silently over-granting.
- Auditability. Log every unwrap and re-wrap operation with actor, timestamp, source and destination key identifiers, and record identifier, then run a final reconciliation pass counting migrated records against the source system's total record count, so completion is a provable, queryable fact, not an assumption that "the job finished."
Part B: when the trigger is active compromise (exfiltrated CI credential, or a suspected extracted vault master key)
- What to freeze first. Revoke or disable the exfiltrated service principal's credentials, or, for a suspected extracted vault master key, immediately rotate and seal the vault and revoke every lease and token issued under the suspect key, before doing anything else, including before fully confirming the extent of the breach. Every additional minute the credential remains valid is pure additional exposure with no offsetting benefit; this is a strict ordering difference from the vulnerability-disclosure case, where you have the luxury of planning the migration first.
- Immediately after the freeze: pull access logs for every decrypt or use of the affected key or credential across its entire suspected-compromise window, not just from the freeze moment forward, since the freeze stops future misuse but tells you nothing about what already happened.
- Cross-team responsibilities. Security or incident response owns the freeze-and-forensics sequence and timeline reconstruction. The platform or infrastructure team that owns the CI system executes the actual credential rotation and audits the CI pipeline itself for how the exfiltration happened, since a compromised credential is a symptom, and the CI system's own security posture (for example, overly broad secrets scoping) is a separate root cause needing its own remediation. Legal or compliance owns the regulatory-notification decision and its clock. Whichever team owns the affected data, not just the credential, independently assesses and communicates impact to data owners or customers. These are genuinely different people with different authorities; this kind of incident fails if one team tries to own all four responsibilities alone.
- Regulatory notifications. If exposed objects contain regulated personal data, breach-notification clocks in many regimes start from the point of confirmed unauthorized access, not from when remediation finishes, and commonly require notification "without undue delay" with an outer bound in some regimes (72 hours is the most frequently cited figure in this space). The exact obligation depends on which regulatory regime applies to the affected data and data subjects, so this determination belongs to your privacy or legal function, not the security team alone.
Worked example: the freeze-order sequence, concretely
1. Revoke the exfiltrated principal, or rotate and seal the suspect vault master key.
2. Snapshot access logs for the full suspected-compromise window.
3. Identify every object ever decrypted under that key or credential.
4. Begin the Part-A confidentiality-preserving re-wrap migration for those specific objects,
on a genuinely urgent timeline, not an "expedited but planned" one.
5. Hand the reconstructed timeline to legal for the notification-clock determination.
6. Post-incident: fix the root cause in CI, the question of how the principal could be
exfiltrated at all, separately from the key-rotation response above.
Trade-offs and pitfalls. The most dangerous mistake is treating an active-compromise trigger with the same unhurried, expedited-but-planned posture as a vulnerability disclosure, freezing too slowly because you are trying to plan a clean migration first. The mirror-image mistake is treating the vulnerability-disclosure case with incident-response urgency, panicking into a rushed, unplanned migration that skips the audit and reconciliation step; in that case you likely have more time than it feels like, since the vulnerability is disclosed, not confirmed exploited against you specifically, and a rushed, unauditable migration creates its own new risk.
Why can't you just hash a password with SHA-256 and call it done? Walk through what a key derivation function actually is (how it differs from a plain hash or a PRF) and compare PBKDF2, bcrypt, scrypt, and Argon2 as password-storage choices: the core mechanism each relies on (iteration count vs memory hardness), typical parameter knobs, and strengths/weaknesses. Then explain how the calculus changes when you're deriving a session key from an already-random shared secret instead of a low-entropy password, and where HKDF fits that case.
Sample Answer
Direct answer
A plain hash like SHA-256 is deliberately fast and has no built-in salt, so two users with the same password get identical hashes, and an attacker holding stolen hashes can try billions of guesses per second on off-the-shelf hardware. A key derivation function (KDF) exists to do the opposite: turn a secret (a password, or an existing high-entropy secret) into cryptographic key material through a process that is either deliberately expensive, for password-based KDFs, to slow down guessing, or that safely spreads entropy into independent-looking keys, for a secret that is already random. PBKDF2, bcrypt, scrypt, and Argon2 are password-hashing KDFs; HKDF is built for the second case.
KDF vs hash vs pseudorandom function (PRF)
- A cryptographic hash function (SHA-256) maps arbitrary input to a fixed-size output, deterministically and quickly, with no secret key. Good for integrity checks; bad for password storage precisely because it is fast.
- A pseudorandom function (PRF), commonly HMAC-SHA256, is a keyed function whose output is computationally indistinguishable from a truly random function's output to anyone without the key. PRFs are building blocks, not complete answers: they say nothing about work factor or memory cost.
- A KDF composes a hash or PRF with an explicit strategy (iteration, memory hardness, or entropy extraction/expansion) to solve "slow this down for guessing resistance" or "expand this safely."
Comparing the four password-hashing KDFs
| Algorithm | Core mechanism | Typical knobs | Strength | Weakness |
|---|---|---|---|---|
| PBKDF2 | Iterates a PRF (usually HMAC-SHA256) c times | Iteration count only | Simple, standardized in NIST SP 800-132, widely available in FIPS-validated libraries | Needs almost no memory, so custom hardware (ASICs, GPUs) can run millions of cheap parallel guesses |
| bcrypt | Repeated Blowfish key schedule | Cost factor (rounds = 2^cost) | Decades of scrutiny, resists naive GPU ports better than PBKDF2 | Fixed, small (roughly 4 KB) memory footprint; silently truncates passwords past 72 bytes |
| scrypt | Sequential memory-hard mixing | Memory/CPU cost N, block size r, parallelism p | True memory hardness (RFC 7914), first widely deployed | More complex to tune correctly; mostly superseded by Argon2 for new work |
| Argon2 | Memory-hard, tunable in three dimensions | Memory m, iterations t, parallelism p | Winner of the 2015 Password Hashing Competition, documented in RFC 9106, three variants for different threat models | Needs careful parameter tuning per target hardware |
The line that matters most: PBKDF2 and bcrypt scale cost mainly by adding sequential compute, which cheap, highly parallel hardware absorbs well. scrypt and Argon2 scale cost by requiring a large memory footprint per guess, and memory is expensive to duplicate across thousands of parallel attempts, which is why they resist GPU/ASIC cracking far better per unit of legitimate server CPU time spent.
When the input is already random: HKDF
Once you have a high-entropy shared secret, for example the output of an ECDHE key exchange, you have no guessing problem to defend against; you have an "I need several independent-looking keys from one secret" problem (a separate encryption key and a MAC key, or per-direction keys). Deliberately slowing that down the way PBKDF2/Argon2 do would only add latency with no security benefit, since there is no offline dictionary attack to resist. HMAC-based key derivation function (HKDF, RFC 5869) is built for exactly this: an "extract" step concentrates the input's entropy into a fixed-length pseudorandom key using HMAC, then an "expand" step derives as much labeled output keying material as needed, bound to a context string so an encryption key and a MAC key derived from the same secret cannot be confused with each other.
Worked example
Deriving 64 bytes of key material (a 32-byte AES key plus a 32-byte HMAC key) from a 32-byte ECDHE shared secret with HKDF-SHA256 is one Expand call producing two concatenated 32-byte outputs. HKDF-SHA256 has a hard ceiling from its own specification: the expand step can produce at most 255 times the hash length, which for SHA-256 (32-byte output) is
255×32=8160 bytes
Deriving a handful of session keys never comes close to that ceiling, which underlines the point: HKDF is built to expand cheaply, not to resist guessing.
Trade-offs and pitfalls
- Argon2id is the current default recommendation over PBKDF2 or bcrypt precisely because of the memory-hardness gap above.
- Using a password KDF where you actually have a random shared secret wastes CPU and adds latency for no security gain; using HKDF where you actually have a low-entropy password gives an attacker no additional cost at all, since HKDF has no configurable work factor.
- Never build a KDF out of raw hash calls yourself; use the vetted PBKDF2/bcrypt/scrypt/Argon2/HKDF implementation in your language's standard cryptography library.
Unlock Full Question Bank
Get access to all Applied Cryptography and Key Management interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.