Key Rotation Strategies
debt(d7/e7/b7/t7)
Closest to 'only careful code review or runtime testing' (d7). Tools like semgrep/trufflehog/gitleaks catch hardcoded keys, but the absence of a rotation policy, missing kid in ciphertext, or a stale KMS schedule is typically found only via review or audit — not flagged in normal CI.
Closest to 'cross-cutting refactor across the codebase' (e7). The quick_fix requires adopting envelope encryption, embedding key IDs in every ciphertext/token, and wiring KMS rotation with overlap — touching every encrypt/decrypt path and stored ciphertext format across services.
Closest to 'strong gravitational pull' (b7). Key management applies across web, cli, queue-worker, and library contexts; every new feature that stores secrets or issues tokens must respect the versioning and overlap scheme, shaping storage formats and deploy processes.
Closest to 'serious trap' (t7). The misconception (rotate only after breach) plus common mistakes (dropping old key immediately, re-encrypting data instead of rotating KEK, no ciphertext versioning) contradict intuition — the 'obvious' rotate-and-replace approach bricks existing data and in-flight sessions.
Also Known As
TL;DR
Explanation
Key rotation is the disciplined practice of retiring and replacing cryptographic keys on a defined schedule, independent of whether a compromise is suspected. Every key has a cryptoperiod - the maximum time it should be used - based on algorithm strength, data volume protected, and threat model. NIST SP 800-57 provides recommended cryptoperiods: signing keys 1-3 years, symmetric data-encrypting keys 1-2 years, key-encrypting keys up to 2 years, session keys per-connection. Rotation is distinct from key generation (creating new material), key storage (protecting it at rest, typically in a KMS or HSM), and key revocation (declaring a key invalid after compromise). Good rotation designs support overlapping validity windows so old ciphertext remains decryptable during transition. Common patterns: (1) Key versioning - each key has an identifier (kid) embedded in ciphertext, tokens, or signatures so the correct key is selected at decrypt/verify time. (2) Envelope encryption with rotating KEKs - rotate the key-encrypting key without re-encrypting all data by re-wrapping only the data keys. (3) Dual-key windows - during rotation both old and new keys are accepted for verification, but only the new key signs new material. (4) Automated rotation via managed services (AWS KMS, GCP Cloud KMS, HashiCorp Vault) which handle scheduling, versioning, and audit logging. Rotation also applies to JWT signing keys, API keys, database credentials, TLS certificates, and OAuth client secrets - each with its own rollover mechanics. The failure mode without rotation is that a single leaked key exposes years of data; with rotation, exposure is bounded to one cryptoperiod.
Common Misconception
Why It Matters
Common Mistakes
- Rotating the key but not versioning ciphertext, so old data becomes undecryptable after cutover.
- Treating rotation as a manual runbook - it drifts, gets skipped, and fails silently until the next audit.
- Rotating the data-encrypting key by re-encrypting terabytes of data instead of rotating the KEK via envelope encryption.
- Removing the old key immediately at rotation instead of keeping an overlap window for in-flight tokens and cached sessions.
- Not distinguishing scheduled rotation from emergency revocation - the two have different urgency, blast radius, and communication needs.
Avoid When
- Ephemeral session keys negotiated per-connection (TLS session keys) - lifetime is already bounded.
- Derived keys from a rotating master via KDF where the master is what actually rotates.
- Prototype code with no production data, where rotation infrastructure is premature overhead.
- Content-addressed encryption (e.g. convergent encryption) where key identity is intrinsic to the data.
When To Use
- Any long-lived symmetric or asymmetric key protecting production data or authentication tokens.
- JWT and OAuth signing keys where a compromise would let an attacker forge sessions.
- Regulated environments (PCI DSS, HIPAA, SOC 2) that explicitly require documented cryptoperiods.
- Multi-tenant systems where per-tenant keys need scheduled rollover to bound blast radius.
Code Examples
// Single hardcoded key, no versioning, never rotated:
class Encryptor {
private const KEY = 'a-secret-32-byte-key-............';
public function encrypt(string $plaintext): string {
$nonce = random_bytes(SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
$ct = sodium_crypto_secretbox($plaintext, $nonce, self::KEY);
return base64_encode($nonce . $ct); // no key id!
}
public function decrypt(string $blob): string {
$raw = base64_decode($blob);
$nonce = substr($raw, 0, 24);
$ct = substr($raw, 24);
// Stuck with this one key forever. Rotation = re-encrypt everything.
return sodium_crypto_secretbox_open($ct, $nonce, self::KEY);
}
}
// Versioned keys with overlap window; new writes use current, reads try any known version.
class VersionedEncryptor {
/** @param array<string,string> $keys keyed by kid, e.g. ['v3' => $bytes, 'v2' => $bytes] */
public function __construct(
private array $keys,
private string $currentKid, // e.g. 'v3'
) {}
public function encrypt(string $plaintext): string {
$nonce = random_bytes(SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
$ct = sodium_crypto_secretbox($plaintext, $nonce, $this->keys[$this->currentKid]);
// kid|nonce|ciphertext - decrypt path can pick the right key.
return $this->currentKid . '|' . base64_encode($nonce . $ct);
}
public function decrypt(string $blob): string {
[$kid, $payload] = explode('|', $blob, 2);
if (!isset($this->keys[$kid])) {
throw new RuntimeException("Unknown key version: $kid");
}
$raw = base64_decode($payload);
$nonce = substr($raw, 0, 24);
$ct = substr($raw, 24);
return sodium_crypto_secretbox_open($ct, $nonce, $this->keys[$kid]);
}
}
// Rotation is now: add 'v4' to $keys, flip $currentKid to 'v4',
// keep 'v3' available until all ciphertext is lazily re-wrapped or expired.
Tags
🤖 AI Guestbook educational data only
References
https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-57pt1r5.pdf
https://cheatsheetseries.owasp.org/cheatsheets/Cryptographic_Storage_Cheat_Sheet.html
https://docs.aws.amazon.com/kms/latest/developerguide/rotate-keys.html
https://developer.hashicorp.com/vault/docs/secrets/transit#key-rotation