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.
Behavioral: describe a concrete project where you designed or implemented cryptography in production. Using the STAR format, explain the problem, what you built, the algorithms and libraries you used, the trade-offs you weighed (security, performance, developer ergonomics), and the measurable outcome. If you don't have direct experience, describe a hypothetical project in the same level of detail.
Sample Answer
A strong answer here uses the STAR method (Situation, Task, Action, Result) to walk through one concrete project: what security requirement forced a cryptography decision, exactly what you built, the specific algorithm and library you chose and why, and a rounded, honest outcome.
STAR framework
- Situation: name the system and the concrete requirement, for example "we stored customer payment metadata and a new compliance mandate required field-level encryption at rest."
- Task: your specific responsibility, for example selecting the primitive and library, implementing it, getting it reviewed, and shipping it.
- Action: what you actually built. Name the primitive (for example AES-256-GCM, an authenticated encryption mode that gives you both confidentiality and tamper detection in one step, used through a vetted library rather than a hand-rolled implementation), and the key management approach (envelope encryption: a per-record data encryption key wrapped by a key encryption key held in a cloud key management service, so the raw key never sits in application memory longer than one operation). Walk through the trade-offs you actually weighed: a stronger security margin versus added latency, a well-documented library API versus building from lower-level primitives, and rotation cost versus the blast radius of a single compromised key.
- Result: describe the outcome in qualitative, rounded terms, for example that the design passed security review with no findings on the cryptography path, or that a later incident on an application server did not expose customer data because the raw key never left the key management boundary. Avoid inventing precise before/after metrics you cannot actually substantiate.
Worked example
Say the project was field-level encryption for a payments-adjacent field. You chose AES-256-GCM with envelope encryption: a data encryption key (DEK) generated per batch of records, wrapped by a key encryption key (KEK) that lives only inside a cloud key management service (KMS) and is never exported in plaintext. The trickiest engineering decision was nonce management, since AES-GCM is completely broken if the same key and nonce pair is ever reused, so you derived the nonce deterministically from a monotonically increasing record ID rather than relying on randomness, and documented that invariant so future maintainers would not break it by reusing the DEK across an unrelated write path.
Trade-offs and pitfalls
Common wrong turns to avoid telling this story: describing a custom or "improved" cryptographic scheme instead of a well-reviewed standard construction, treating key rotation as an afterthought instead of a day-one design decision, and picking a project that is really a tour of everything you have touched rather than one focused story with real depth. Be ready with a second, smaller example in case the interviewer pushes for more detail on a specific part.
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.
Analyze the performance and scalability trade-offs of envelope encryption at internet scale: the CPU cost of AEAD on service hosts, the latency and overhead of KMS calls to unwrap key-encryption keys, client-side caching strategies for unwrapped keys, TTL selection, and throttling policies to protect the KMS from being overwhelmed. When fetching wrapped keys per request becomes a bottleneck, what do you actually cache, how do you invalidate that cache safely on rotation (including using mlock-style in-memory secure caches), and what monitoring signals would tell you the cache itself has become a security risk?
Sample Answer
Direct answer
At internet scale, the CPU cost of the actual AEAD encryption (AEAD, or Authenticated Encryption with Associated Data, the class of symmetric cipher such as AES-256-GCM that both encrypts data and detects tampering) is rarely the bottleneck, modern hardware does multi-gigabyte-per-second AES-GCM with hardware acceleration. The real constraint is the per-request network round trip and rate limit on calls to the KMS to unwrap a data-encryption key under the account's key-encryption key. The fix is caching the unwrapped DEK locally rather than calling the KMS on every operation, with a TTL, periodic revalidation, and invalidation strategy that bounds how long a compromised or rotated key can keep being used from a stale cache, plus monitoring that watches the cache itself for signs it has become a liability rather than an optimization.
Structured elaboration
CPU cost of AEAD on service hosts
- AES-256-GCM, or ChaCha20-Poly1305 on hardware without AES acceleration, with hardware support such as AES-NI on most modern server CPUs, commonly achieves multiple gigabytes per second per core, so for the overwhelming majority of workloads the symmetric encryption step itself is not where capacity-planning effort should go.
Latency and overhead of KMS calls
- Every DEK unwrap is a network round trip to the KMS, typically single-digit to double-digit milliseconds, plus the KMS's own per-account or per-key request-rate limits. At high request volume, calling the KMS on every encrypt or decrypt turns a fast local operation into a network-bound one and can hit throttling limits that have nothing to do with your actual compute capacity.
Client-side caching strategies
- Cache the unwrapped DEK, never the KEK, which should never leave the KMS or HSM boundary at all, keyed by the wrapped DEK's own identity, a hash or the wrapped ciphertext itself, since that uniquely identifies which unwrap result it corresponds to.
- Cache in process memory only, never write the unwrapped key to disk or to a shared cache tier that isn't equally trusted, the whole point of envelope encryption is that plaintext keys have a small, controlled footprint.
TTL selection and periodic revalidation
- TTL is a direct trade between KMS load, a longer TTL means fewer calls, and exposure window, a longer TTL means a cached plaintext key survives longer after something changes, a rotation, a revocation, a host compromise. A common starting point is minutes, not hours, tuned against measured KMS call volume and the organization's actual risk tolerance for that data classification.
- Beyond a pure TTL, revalidate cached entries against the KMS on a schedule shorter than the TTL itself for high-sensitivity keys, a lightweight check that the wrapped DEK's KEK version is still current, which catches a rotation or revocation faster than waiting for a full TTL expiry without needing a full push-based invalidation pipeline.
Invalidating the cache safely on rotation
- Tag every cached DEK entry with the KEK version it was unwrapped under. When a rotation event is published, or detected via a version mismatch on the next wrap or unwrap call, proactively evict cache entries tied to the old version rather than waiting for their TTL to lapse naturally, bounding exposure to the time it takes the rotation event to propagate instead of the full TTL window.
- For revocation specifically, as opposed to routine rotation, a proactive push-based invalidation, a pub/sub event telling every cache to drop entries tied to the revoked key immediately, is worth the added complexity over TTL-only expiry, since revocation implies urgency routine rotation usually doesn't.
Secure in-memory caching, mlock-style
- Pin the memory pages holding plaintext key material so the OS never swaps them to disk, mlock or mlockall on POSIX systems, and mark that memory to be excluded from core dumps, madvise with MADV_DONTDUMP on Linux, since a core dump or swap file containing live plaintext keys turns an unrelated crash or forensic snapshot into a key-material leak.
- Zero the memory, a constant-time wipe, as soon as a cached entry is evicted or expires, rather than leaving plaintext key bytes sitting in freed-but-unzeroed memory that a later bug could expose.
Throttling policy to protect the KMS
- Client-side rate limiting and backoff on unwrap calls, so a cache-stampede, many hosts missing cache at once, doesn't overwhelm the KMS, plus server-side per-key or per-principal quotas on the KMS itself as a backstop. Treat the KMS's request budget as a shared, finite resource across the whole fleet, not something any one service can assume it has unlimited access to.
Monitoring signals that the cache has become a security risk
- Cache size growing well beyond what the working set of active keys should require, a signal of a TTL misconfiguration, a key being fetched more broadly than intended, or a leak in eviction logic.
- A successful decrypt against a key that monitoring elsewhere shows as revoked or rotated out, direct proof a cache is serving stale, no-longer-valid key material.
- An unexpected spike in process memory dumps or core dumps in an environment where the plaintext-key cache lives, exactly the artifact that would expose cached keys if it escaped the host.
- TTL configuration drifting upward over time is worth its own periodic audit, since cache TTLs tend to only get longer under performance pressure unless someone is explicitly watching.
Worked example
If a service performs 50,000 encrypt or decrypt operations a second and the DEK cache achieves a 95% hit rate, only 50,000 times 0.05, or 2,500, unwrap calls a second reach the KMS, versus 50,000 a second with no caching at all, a twentyfold reduction in KMS load that is the entire reason this design earns its complexity. If that hit rate silently degrades to 50%, a misconfigured TTL, a rotation storm, an application bug bypassing the cache, KMS load jumps to 25,000 a second, a tenfold increase over the 2,500 baseline that could trip throttling limits the capacity plan never accounted for, exactly what the cache-hit-ratio monitoring above needs to catch before it becomes an incident.
Trade-offs and pitfalls
Common wrong turn: setting a long TTL purely to minimize KMS calls without stating the exposure trade-off out loud, optimizing one number, cost and latency, while silently accepting a much larger security cost. Common wrong turn: caching the KEK instead of the DEK for convenience, defeating the entire purpose of envelope encryption, since the KEK is exactly the thing that should never leave the KMS or HSM boundary in usable form. Senior signal: treating cache-hit ratio as a monitored production metric with its own alerting, not a one-time capacity-planning assumption, since the numbers above only hold as long as that ratio holds in production.
A cloud VM image was restored from a snapshot, and you discover weak keys were generated on boot because of low entropy. Describe your immediate detection and mitigation steps for affected instances, and the longer-term architectural changes you'd make to prevent entropy-starvation problems across the fleet.
Sample Answer
Direct answer
This is the classic virtual machine (VM) snapshot entropy-starvation failure: restoring multiple
instances from the same snapshot can leave each one's random-number generator seeded from the exact
same internal state, so keys generated shortly after boot can be identical or closely related across
"different" instances. Immediately rotate every key generated at or near first boot on any instance
restored from that snapshot lineage, and longer term, stop generating long-lived keys until the
operating system's cryptographically secure pseudo-random number generator (CSPRNG) is confirmed to be
seeded with genuinely fresh, instance-unique entropy.
Structured elaboration
- Why this happens. A snapshot captures the entropy pool's internal state at the moment it was
taken. When several instances restore from that same snapshot, each kernel CSPRNG (for example
Linux's/dev/urandomand itsgetrandom()system call) can start in the exact same seeded state, if
a key-generation event fires before the operating system has mixed in enough new, instance-unique
entropy (hardware interrupt timing, boot-time jitter), two "different" restored instances can produce
identical or related output. For RSA or Digital Signature Algorithm (DSA) key generation specifically,
this can leak the private key entirely via shared-prime attacks (an RSA public key's modulus is the product of two secret prime numbers, so if two keys accidentally reuse one of those primes, taking the greatest common divisor of their two public moduli recovers that shared prime instantly, and from it both private keys can be fully reconstructed): comparing keys across a fleet with a
batch greatest-common-divisor (GCD) computation reveals any pair that shares a prime factor, and
sharing even one prime factor breaks both keys completely. - Immediate detection. Identify every instance restored from the affected snapshot or golden-image
lineage, and every key or credential generated at or shortly after its first boot: Transport Layer
Security (TLS) host keys, Secure Shell (SSH) host keys, and any application-level "generate on first
boot" logic. A fast, practical triage technique is running a batch GCD comparison across all the
fleet's RSA public keys: if any two share a prime factor, both are broken, and this is proof by
itself, it does not require separately proving that entropy was actually low on either device. - Immediate mitigation. Force regeneration of every affected key or credential from a properly
seeded instance, never from the same snapshot lineage, and revoke or replace any certificates issued
for the old, potentially weak keys. Treat this exactly like any other confirmed key-compromise
incident, a low-entropy key is a compromised key whether or not anyone has exploited it yet. - Longer-term architectural changes.
- Ensure golden images and first-boot or cloud-init logic never perform long-term key generation
until sufficient entropy is confirmed available. Modern kernels already blockgetrandom()until
the CSPRNG is properly initialized specifically to prevent this class of bug, so the real fix is
often simply not bypassing that protection with an older or non-blocking random-source call, and
making full use of the platform's hardware entropy source, most major cloud providers inject
genuine hardware entropy into VMs specifically to address this problem. - Never bake unique, long-term secrets (host keys, node identity keys) into a golden image or
snapshot at all; generate them fresh on genuine first boot only, and make snapshot or clone
operations explicitly clear or regenerate anything that must be unique per instance. Standard
cloud-init mechanisms for regenerating SSH host keys on clone are the off-the-shelf version of this
fix, and should be treated as mandatory, not optional, for any image used to spawn multiple
instances. - Add a provisioning gate that verifies genuine entropy availability, or explicitly waits for the
kernel's CSPRNG-ready signal, before allowing any key-generation step to run, rather than trusting
that "the VM finished booting" implies "the VM is ready to generate secrets."
- Ensure golden images and first-boot or cloud-init logic never perform long-term key generation
Worked example
Large-scale internet scans of public RSA and DSA keys have found that a meaningful, non-trivial
fraction of examined keys share a prime factor with at least one other key on the internet, almost all
traced back to exactly this kind of boot-time entropy problem on embedded and virtualized systems. This
is precisely why batch GCD across a fleet is a real, practical detection technique used in production
incident response, not a theoretical concern: it is far cheaper computationally than trying to factor
each key individually, since it only needs pairwise GCD comparisons, but it does require you to
actually have collected every public key in the fleet first, which is itself a strong argument for
centrally inventorying every generated key as a prerequisite for ever being able to run this check.
Trade-offs & pitfalls
- Rotating the affected credentials without also fixing the root cause, the image or provisioning
logic's entropy handling, simply recreates the same vulnerability at the next scale-out event. - This is not a "slightly weaker" key; a successful shared-factor attack recovers the FULL private key.
Urgency and response should match a confirmed full compromise, not a minor weakness. - Batch GCD detection is cheap to run but only as good as your key inventory; if you cannot enumerate
every key your fleet has ever generated, you cannot run this check against all of them, which argues
for building that inventory before you need it, not during the incident.
Write a Terraform configuration snippet that provisions an AWS KMS symmetric key with automatic key rotation enabled, a dedicated admin role with restricted permissions, and a grant that lets a Lambda function encrypt/decrypt without ever exposing the key material. Include the relevant IAM policy and explain how this enforces separation of duties.
Sample Answer
Approach. Provision a symmetric KMS key with automatic annual rotation enabled, a dedicated admin role that can manage the key but never use it for encrypt/decrypt, and a KMS grant, not a key policy statement, that lets a Lambda function's execution role perform encrypt/decrypt/generate-data-key operations without ever being able to export, delete, or otherwise administer the key. Separation of duties comes from splitting administration (the admin role, via the key policy) from usage (the Lambda role, via a scoped grant) so no single principal can both use and manage the same key.
Code. This validates cleanly against the real hashicorp/aws provider schema (terraform validate, provider ~> 5.0); it was not applied against a live AWS account, since that needs real credentials and would create billed resources, but validation confirms every argument and resource type here is syntactically and semantically correct for the pinned provider version.
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0"
}
}
}
provider "aws" {
region = "us-east-1"
}
data "aws_caller_identity" "current" {}
resource "aws_kms_key" "app_data_key" {
description = "Symmetric KMS key for app-data envelope encryption"
key_usage = "ENCRYPT_DECRYPT"
customer_master_key_spec = "SYMMETRIC_DEFAULT"
enable_key_rotation = true
deletion_window_in_days = 30
policy = jsonencode({
Version = "2012-10-17"
Statement = [
{
Sid = "EnableRootAccountFullAccess"
Effect = "Allow"
Principal = { AWS = "arn:aws:iam::${data.aws_caller_identity.current.account_id}:root" }
Action = "kms:*"
Resource = "*"
},
{
Sid = "AllowKeyAdmin"
Effect = "Allow"
Principal = { AWS = aws_iam_role.kms_admin.arn }
Action = [
"kms:Create*", "kms:Describe*", "kms:Enable*", "kms:List*",
"kms:Put*", "kms:Update*", "kms:Revoke*", "kms:Disable*",
"kms:Get*", "kms:Delete*", "kms:TagResource", "kms:UntagResource",
"kms:ScheduleKeyDeletion", "kms:CancelKeyDeletion",
]
Resource = "*"
},
]
})
}
resource "aws_iam_role" "kms_admin" {
name = "kms-app-data-admin"
assume_role_policy = jsonencode({
Version = "2012-10-17"
Statement = [{
Effect = "Allow"
Principal = { AWS = "arn:aws:iam::${data.aws_caller_identity.current.account_id}:root" }
Action = "sts:AssumeRole"
}]
})
}
resource "aws_iam_role" "app_lambda" {
name = "app-data-encrypt-decrypt-lambda"
assume_role_policy = jsonencode({
Version = "2012-10-17"
Statement = [{
Effect = "Allow"
Principal = { Service = "lambda.amazonaws.com" }
Action = "sts:AssumeRole"
}]
})
}
# Grant, not a key-policy statement: lets the Lambda role use the key for
# crypto operations without ever being able to manage or delete it.
resource "aws_kms_grant" "lambda_usage_grant" {
name = "lambda-encrypt-decrypt-grant"
key_id = aws_kms_key.app_data_key.key_id
grantee_principal = aws_iam_role.app_lambda.arn
operations = ["Encrypt", "Decrypt", "GenerateDataKey"]
}
# The Lambda role also needs an identity-based policy naming the key ARN;
# the grant alone does not substitute for this on the caller's side.
resource "aws_iam_role_policy" "app_lambda_kms_usage" {
name = "allow-kms-encrypt-decrypt"
role = aws_iam_role.app_lambda.id
policy = jsonencode({
Version = "2012-10-17"
Statement = [{
Effect = "Allow"
Action = ["kms:Encrypt", "kms:Decrypt", "kms:GenerateDataKey"]
Resource = aws_kms_key.app_data_key.arn
}]
})
}
output "kms_key_arn" {
value = aws_kms_key.app_data_key.arn
}
Key points. Separation of duties here is enforced by who can do what to the key, not by naming: kms_admin appears only in the key policy's admin statement (create, describe, rotate, schedule deletion) and never in an operations list; app_lambda appears only in the grant and the matching identity policy (encrypt, decrypt, generate a data key) and never in an admin action. Neither role's permission set overlaps the other's, so compromising either role alone cannot both use and administer the key. enable_key_rotation = true turns on AWS's automatic annual key-material rotation, which happens transparently: existing ciphertexts stay decryptable across a rotation with no re-wrapping step required, unlike a deliberate migration to an entirely new key, which does require re-wrapping every existing ciphertext since the old key material is being retired rather than merely rotated in place.
Complexity and operational cost. This is a single terraform apply provisioning a fixed, small set of resources (one key, two roles, one grant, one inline policy), O(1) API calls regardless of how many callers eventually use the key; the ongoing operational cost is standard Terraform drift detection on each plan, not anything specific to this configuration.
Edge cases. If app_lambda's role ARN changes (for example, the role is recreated rather than updated), the existing grant becomes orphaned and a new one must be created and the old one explicitly revoked, since grants are tied to the grantee principal's ARN, not to a stable logical name. If the key's deletion window (30 days here) is too short for your compliance retention requirements, increase it, deletion is intentionally not immediate specifically to allow recovery from an accidental terraform destroy. A root-account statement with "Action": "kms:*" is intentionally broad (it is the standard AWS-recommended safety net so the account is never locked out of its own key), but it means anyone who can assume the account root or an equivalently privileged role bypasses the separation of duties modeled here entirely; that is a real, accepted trade-off of the default AWS key-policy pattern, not an oversight.
Unlock Full Question Bank
Get access to all 24 Applied Cryptography and Key Management interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.