Practices and techniques for implementing cryptography and related security controls in application code so that cryptographic guarantees are preserved in real world systems. Topics include correct algorithm selection and parameter choices, secure random number generation and entropy handling for keys and nonces, safe key generation and lifecycle management, and secure storage and zeroing of sensitive data in memory. Implementation hardening covers constant time implementations to avoid timing attacks, protections against cache and power side channel attacks, proper use of padding and avoidance of padding oracle vulnerabilities, correct initialization vector and nonce usage to avoid reuse, and awareness of compiler and optimization effects that can break security properties. It also covers secure use of cryptographic libraries and avoiding misuse of primitives, secure password hashing choices, avoidance of custom or home grown cryptography, secure error handling to prevent information leaks, secrets management to avoid hard coded credentials, dependency and supply chain management to avoid vulnerable libraries, input validation and output encoding when cryptography interacts with untrusted input, and testing and verification approaches such as code review, static analysis, runtime testing, and fuzzing to find implementation flaws.
EasyTechnical
49 practiced
Explain the components of a secure random number generator (RNG) used for keys and nonces in production applications. Distinguish between entropy sources (TRNG), CSPRNG/DRBG, seeding/reseeding, and common developer mistakes (e.g., using rand()/srand(), predictable seeds in VMs). Describe practical checks you would put into deployment to detect RNG failures.
Sample Answer
**Overview — components of a secure RNG**- **Entropy source (TRNG):** hardware or OS-provided unpredictable events (thermal noise, ring oscillators, interrupt timings). Provides raw, high-quality entropy bits. Must be measured and health-checked (min-entropy estimates).- **CSPRNG / DRBG:** deterministic algorithm (e.g., NIST SP 800-90A constructions, Fortuna, ChaCha20-DRBG) that expands entropy into cryptographically strong pseudorandom output. Design ensures next-bit unpredictability and resistance to state compromise (forward/backward secrecy when properly constructed).- **Seeding / reseeding:** TRNG output seeds the DRBG at initialization and periodically reseeds to recover entropy after compromise or long runtime. Reseed intervals should balance performance and security; use entropy estimation and conservative thresholds.**Common developer mistakes**- Using non-cryptographic RNGs (rand(), srand(), linear congruential generators).- Predictable seeds: time-only seeds, fixed seeds in configs, or cloned VM images sharing PRNG state.- Ignoring OS RNG APIs (e.g., /dev/urandom, getrandom, CryptGenRandom) or disabling entropy collection.**Practical deployment checks**- Monitor entropy pool size and health metrics from the OS/hardware.- Validate DRBG self-tests and startup reseed occurred; fail boot if not.- Detect duplicate outputs across instances (e.g., sample fingerprints at boot and compare to fleet).- Run continuous statistical/health tests and alert on failures (repetition, stuck outputs).- Log and alert VM clones or snapshots that boot without entropy reseed.
EasyTechnical
57 practiced
Explain why hard-coding cryptographic secrets (keys, API tokens, certificates) in source code or container images is dangerous. Provide secure alternatives (cloud KMS/HSM, secrets vaults, environment injection), and describe patterns for fetching, caching, and rotating secrets safely in CI/CD and production.
Sample Answer
**Why hard-coding secrets is dangerous**Embedding keys, tokens, or certs in source or images creates irreversible leakage vectors: VCS history, forks, CI logs, image registries, and attacker-accessible images. It increases blast radius (same secret reused across environments), prevents proper rotation, and undermines cryptographic assurances (key compromise → loss of confidentiality, integrity, and non-repudiation).**Secure alternatives**- Cloud KMS / HSM: store keys in hardware-backed vaults; perform cryptographic ops (sign/decrypt) without exporting raw key material.- Secrets vaults (HashiCorp Vault, AWS Secrets Manager): dynamic, access-controlled secrets, audit logs, short TTLs.- Environment injection via secure runtime (secret sidecar, CSI driver) or ephemeral tokens issued at container start.**Patterns for fetching, caching, rotating**- CI/CD: retrieve ephemeral credentials at job start using OIDC or short-lived role-assumption; never store long-lived tokens in pipeline config.- Production fetch: fetch from vault at bootstrap using instance identity (mTLS, instance metadata + signed assertions); prefer server-side crypto ops in KMS/HSM.- Caching: keep secrets in memory only, encrypted at rest if persisted, use in-memory caches with TTL and automatic refresh before expiry; limit cache scope and lifetime.- Rotation: automate rotation via vault/KMS APIs, use key versioning and gradual re-encryption; support key identifiers and key-agility in protocols so older ciphertext can be rewrapped.- Access controls & telemetry: enforce least privilege, MFA for key operations, audit every access, and trigger alerts on anomalous use.As a cryptographer I prioritize key isolation (HSM), minimal key exposure, and cryptographic agility so compromise recovery is practical.
HardSystem Design
61 practiced
Design a system to seal secrets in the cloud so that only a specific service binary running on attested hosts can unseal them, using TPM/HSM-based attestation. Define the threat model, attestation and key-provisioning flow, lifecycle management (rotation, revocation), recovery procedures for lost attestation, and practical deployment challenges (CI/CD, upgrades, rollbacks).
Sample Answer
**Threat model**- Adversary: remote network attacker, malicious cloud operator, compromised host OS, stolen binary, or firmware-level attacker. - Trust roots: vendor HSM/TPM, cloud KMS, signing CA for binaries. Assume TPM is hardware-rooted, attestation keys non-exportable. Do not trust OS/userland integrity unless attestation says so.**Attestation & key-provisioning flow**1. Binary image signed by CI private key; image hash embedded in attestation policy.2. Host TPM/EK -> AIK (attestation key) signs PCRs + nonce from Sealing Service (SS).3. SS verifies TPM quote via CA, checks PCRs against expected measurements and binary signature provenance.4. If OK, SS generates ephemeral symmetric sealing key K_enc wrapped by the cloud HSM under a key K_hsm and sealed to the TPM public key (or ECC key agreement with TPM).5. Binary receives sealed blob; TPM unseals only when PCRs match, yielding K_enc to decrypt secrets.**Lifecycle (rotation, revocation)**- Rotate K_hsm periodically in HSM with key-wrapping: rewrap sealed blobs atomically.- Maintain attest-policy versions; revoke binary/host by adding PCR/policy to denylist in SS; CRL for compromised AIKs.- Use epoch/nonce in sealed blobs to force refresh after rotation.**Recovery for lost attestation**- Out-of-band recovery: require multi-party approval (M-of-N via HSM) to re-encrypt secrets to a new attested identity; log and require operator attestation with paper wallet + secure enclave attestation.- Short-term emergency keys with strong audit trail; time-limited and require HSM quorum.**Practical deployment challenges**- CI/CD: sign images in pipeline; embed reproducible build info; ensure attestation policy updates propagated.- Upgrades/rollbacks: include policy allowing measured boot chain variants or require staged rollout with new measurement allowances; maintain rollback-protection PCRs.- Scalability: use HSM-backed service for global key wrapping and caching of attestation results with TTL.- Observability & testing: simulate TPM quotes in staging; test rotation/recovery regularly.- Usability trade-offs: balance strict PCR policies vs operational flexibility; prefer layered policies (strict for prod, relaxed for staging).This design enforces hardware-rooted secrecy: secrets unseal only when the exact signed binary runs on hosts with expected measured state validated by TPM/HSM-backed attestation and strong operational controls.
MediumTechnical
46 practiced
You are deploying many VM instances from a base image in a cloud environment. Describe the entropy-related risks this introduces (identical RNG state across clones, low entropy at boot), how that can break key generation or TLS, and present concrete mitigation measures during image design and boot sequence: health checks, reseeding strategies, use of hardware RNGs or cloud provider randomness services, and attestation.
Sample Answer
**Short answer (risk summary)** Cloning VMs from a single base image can replicate identical RNG state and produce low-entropy boots. That risks generating identical or weak private keys, predictable nonces (breaking ECDSA/DSA/GCM), and TLS/SSH keys that are duplicated or cryptographically broken.**Why it breaks crypto** - Identical seed state => identical DRBG outputs => identical keys/IVs/nonce streams. - Low entropy at early boot => deterministic or biased key material; reuse of nonces enables private-key recovery for many signature/cipher schemes.**Concrete mitigations — image design**- Remove saved RNG state from images (e.g., clear /var/lib/systemd/random-seed) before imaging. - Integrate a hardware- or platform-based entropy source: enable virtio-rng, RDRAND/RDSEED, or a TPM HWRNG driver in the image. - Include a small boot-time agent that verifies entropy availability and blocks crypto-critical services until sufficient entropy is present.**Boot-sequence reseeding strategies**- Reseed DRBG early from HWRNG or cloud randomness service (see below). Use kernel getrandom() to seed userspace CSPRNGs. - Run rngd/erd to feed the entropy pool from HWRNG and verify entropy increase. - Delay private-key generation and TLS server start until getrandom() indicates the pool is initialized (or check /proc/sys/kernel/random/entropy_avail on systems where appropriate).**Use of provider/hardware randomness**- Prefer robust HWRNGs (RDSEED/RDRAND as supplement, not sole source) and feed into kernel entropy. - Use cloud provider randomness APIs (e.g., AWS Entropy Service, Google Cloud HSM-backed randomness) to reseed at first boot over authenticated channels. - For highest assurance, use TPM 2.0 or KMS/HSM-backed key generation so private keys are generated inside attested hardware and never derived from VM entropy.**Health checks & attestation**- Add boot health-checks to fail fast: entropy threshold tests, key-duplication detectors (compare key fingerprints to inventory), and logging/alerts. - Use attestation (TPM, cloud attestation) to prove the VM booted with expected image and that HWRNG or provider reseed occurred; tie this to automated key provisioning from a KMS/HSM.**Operational controls**- Rotate keys if low-entropy boot is detected; require re-provisioning from KMS. - Monitor for reused certificates/keys across fleet. - Document deterministic behavior assumptions, and enforce CI image hygiene to avoid accidental seed snapshots.I would implement: image cleanup hooks, a boot agent that calls getrandom()/rngd and blocks TLS until entropy strong, fallback to cloud KMS/HSM key issuance, and TPM-based attestation for assurance.
HardTechnical
61 practiced
Design an experiment to detect cache-based side-channel leakage from a cryptographic routine running on a shared cloud host. Define the attacker model (co-residency, privileges), measurements you would collect (timing, cache-probing traces), statistical analysis to detect leakage, and mitigation steps to harden the routine if leakage is confirmed.
Sample Answer
**Attacker model (assumptions)** - Co-residency on same physical core/socket or same last-level cache (LLC). - Attacker is unprivileged VM/userland process; no kernel or hypervisor access. - Able to schedule frequent probe/evict loops and synchronize loosely (wall-clock) with victim activity; may trigger victim operations (chosen-input) if API available.**Measurements to collect** - High-resolution timing of probe sets (prime+probe) and/or shared-line accesses (flush+reload) to build cache-usage traces. - Timestamped victim invocation markers and input labels when possible. - System telemetry: core-PID affinity, CPU frequency, noise indicators (context switches, interrupts). - Replay many traces per input value (thousands) to accumulate statistics.**Detection / statistical analysis** - Preprocess: align traces to invocation, normalize by background noise, filter out outliers. - Feature extraction: per-cache-set hit/miss counts, latencies, time-series windows, PCA for dimensionality reduction. - Hypothesis testing: use mutual information between secret-dependent input bits and cache features; compute empirical MI and compare to shuffled-label baseline (permutation test) to get p-values. - Classification: train simple classifiers (logistic regression / random forest) to predict secret bits; evaluate ROC/AUC and compute advantage over random guessing. - Significance: require low p-value (e.g., <0.01) and reproducible classifier accuracy across cross-validation folds.**Mitigations if leakage found** - Algorithmic: switch to constant-memory-access routines (table-less implementations, algorithmic blinding). - Microarchitectural: add cache-line alignment/padding, avoid secret-indexed lookups, use arithmetic-only implementations or bit-slicing. - OS/Deployment: enforce core isolation, disable hyper-threading, use page coloring or cache partitioning (CLOS/Intel CAT). - Countermeasures validation: repeat detection experiment after each mitigation; aim for MI and classifier performance at noise levels (no distinguishability).**Why this approach** Combines realistic attacker model, measurable cache signals, rigorous information-theoretic and ML-based detection, and layered mitigations that preserve performance-security trade-offs.
Unlock Full Question Bank
Get access to hundreds of Secure Cryptographic Implementation interview questions and detailed answers.