iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

Key Management

Crypto key management: generation, storage, rotation, recovery, and the lifecycle controls that keep secrets actually secret.

Crypto — key management

EXAMPLE
# ===== Lifecycle =====
# Generate -> distribute -> use -> rotate -> destroy
# Every stage has rules. Skipping any one of them is where leaks happen.

# ===== Generation =====
# Always from a CSPRNG (OS-provided):
#   openssl rand -hex 32
#   crypto.randomBytes(32) in Node
#   secrets.token_bytes(32) in Python
# Never from a deterministic seed for production secrets.

# Use vetted key derivation when deriving from a password:
#   Argon2id, scrypt, bcrypt for password->key
#   HKDF for key->key derivation (e.g. context-bound subkeys)

# ===== Storage =====
# Best (in 2026): KMS / HSM
#   - AWS KMS, GCP KMS, Azure Key Vault, HashiCorp Vault
#   - Keys never leave the HSM; you call sign/decrypt APIs
# Good: Encrypted at rest with a master key from a KMS (envelope encryption)
# OK:   Sealed secrets (Bitnami, SOPS) in git when used with KMS-managed keys
# Bad:  Plain in .env, environment variables logged, configmaps
# Worst: Source code, log files, public buckets

# Envelope encryption (the workhorse pattern):
# 1. Generate a random Data Encryption Key (DEK)
# 2. Encrypt data with DEK (AES-GCM)
# 3. Encrypt DEK with KMS Key Encryption Key (KEK)
# 4. Store ciphertext + wrapped DEK
# Decrypt: KMS unwraps DEK; app decrypts with DEK; DEK is zeroised after use.

# ===== Access control =====
# Least privilege per role:
#   service A can sign  with key X
#   service B can verify with key X
# IAM policies in cloud KMS; ACLs in Vault.

# Audit every key use; export to SIEM.

# ===== Rotation =====
# - Schedule: 90 days (signing), 1 year (encryption KEKs), 6 months (API tokens)
# - Use KEY VERSIONS in KMS; old versions decrypt history, new version encrypts new data
# - Background re-encrypt loops migrate ciphertext to the latest version
# - Never delete old key versions while ciphertext referencing them still exists

# ===== Recovery =====
# What happens if the key is lost?
# - Cloud KMS replicas + multi-region keys mitigate region loss
# - Key escrow (with extreme care) for legal compliance
# - Document recovery RUNBOOK before go-live
# - PRACTICE the recovery — half the time runbooks lie

# ===== Compromise =====
# What happens if you suspect the key is leaked?
# 1. Disable the key in KMS (stops further use)
# 2. Rotate IMMEDIATELY
# 3. Re-encrypt critical data with new key
# 4. Audit logs to identify scope
# 5. Notify affected parties / regulators per policy

# ===== Distribution =====
# - Never email or chat keys; out-of-band rotation
# - Service-to-service: short-lived OAuth tokens, mTLS certs, KMS-issued JWTs
# - Human access: SSH certificates with short TTL > permanent SSH keys

# ===== Storage formats =====
# - PEM: human-readable, common
# - DER: binary
# - JWK / JWKS: JSON Web Keys (popular for OIDC)
# - PKCS#12 (.p12 / .pfx): combined cert + key + chain (often password-protected)

# ===== Common gotchas =====
# - Keys in environment variables -> end up in process listings / dumps
# - Sharing one signing key across teams -> blast radius
# - Forgetting to rotate after a developer leaves
# - KMS keys in same account as the data they protect (bad blast radius)

# ===== Patterns to internalise =====
# - KMS / HSM for all production keys
# - Envelope encryption for application data
# - Rotation schedule + automation
# - Documented + practised recovery + compromise playbooks
# - Audit logs into SIEM with alerts on unusual key use

# ===== Pitfalls =====
# - 'It is just a dev key' that ends up in prod
# - No rotation policy -> keys age forever
# - Plain-text private keys in container images
# - Storing the master key in the same secret store it is meant to unlock

Why it matters

Key management is a lifecycle, not a setting. Generate from CSPRNG, store in KMS, derive with HKDF, rotate on a schedule, document recovery + compromise, audit every use. Most production crypto incidents trace back to key handling, not algorithm choice. Get the lifecycle right and the math takes care of itself.

Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.

Example

Example
// Generate → store in KMS / HSM → rotate → audit.
// Never check keys into git. Use env injection only at runtime.
// Add 'kid' (key id) to JWTs so you can rotate without revocation.
Try it Yourself »

Discussion

Loading…