TExcelTAD
Home › Applied Cryptography: Ciphers, Hashes, Signatures, PKI & TLS › Key Management, Rotation and Envelope Encryption

Key Management, Rotation and Envelope Encryption

Cryptography converts a large secret (your data) into a small one (a key). It doesn't remove the secret; it moves it. Most real-world crypto failures in mature organisations are therefore key-management failures: the AES key in the same Git repository as the encrypted data, a signing key on a build server anyone can SSH into, a database encryption key that has never been rotated because nobody knows what would break, a key deleted by mistake with no backup. This lesson covers the lifecycle, the envelope-encryption pattern that cloud KMSs are built on, and HSMs.

The key lifecycle

NIST SP 800-57 Part 1 describes the stages every key goes through:

  1. Generation: from a CSPRNG or inside an HSM, with the right size and algorithm.
  2. Distribution and storage: never in source code, images or tickets; in a KMS, HSM or secrets manager with access control and audit (Secrets policy, how secrets leak).
  3. Use: one purpose per key (encryption, signing, MAC, key wrapping), with a cryptoperiod: how long, or for how much data, it may be used.
  4. Rotation: a new version replaces the old one for new operations; the old one is kept only to decrypt or verify existing data.
  5. Revocation and compromise recovery: a procedure to replace a key quickly and to know what it protected.
  6. Destruction: when no data needs it any more, destroy all copies, including backups.

Envelope encryption

Encrypting terabytes directly with a key that lives in an HSM would mean sending all the data to the HSM. Instead, systems use two layers:

  • a data encryption key (DEK), random, used locally with AES-GCM for one record, file or batch;
  • a key encryption key (KEK), kept in the KMS or HSM, used only to wrap (encrypt) DEKs.

The wrapped DEK is stored next to the ciphertext. To decrypt, the application asks the KMS to unwrap the DEK (an audited, access-controlled call), decrypts locally and forgets the DEK. AWS KMS (GenerateDataKey), Google Cloud KMS, Azure Key Vault, HashiCorp Vault's transit engine (Vault transit) and Kubernetes secret encryption all work this way.

python · try it yourself
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
from cryptography.hazmat.primitives.keywrap import aes_key_wrap, aes_key_unwrap

# The "KMS": key-encryption keys (KEKs) by id. In a real KMS or HSM they never leave the device.
KMS = {"kek-2025": bytes.fromhex("11" * 32), "kek-2026": bytes.fromhex("22" * 32)}   # fixed lab keys
def kms_wrap(kid, dek): return aes_key_wrap(KMS[kid], dek)          # AES key wrap, RFC 3394
def kms_unwrap(kid, blob): return aes_key_unwrap(KMS[kid], blob)

def encrypt_record(record_id, data, kid, dek, nonce):
    # real code: dek = AESGCM.generate_key(256) per record or per batch; nonce = os.urandom(12)
    ct = AESGCM(dek).encrypt(nonce, data, record_id.encode())      # the record id is bound as AAD
    return {"id": record_id, "kid": kid, "wrapped_dek": kms_wrap(kid, dek).hex(), "nonce": nonce.hex(), "ct": ct.hex()}

def decrypt_record(rec):
    dek = kms_unwrap(rec["kid"], bytes.fromhex(rec["wrapped_dek"]))
    return AESGCM(dek).decrypt(bytes.fromhex(rec["nonce"]), bytes.fromhex(rec["ct"]), rec["id"].encode())

rec = encrypt_record("cust-4711", b"IBAN XX00 LAB 0000 0000", "kek-2025", bytes.fromhex("ab" * 32), bytes(12))
print("stored:", {k: (v[:16] + "...") if len(v) > 16 else v for k, v in rec.items()})
print("wrapped DEK:", len(bytes.fromhex(rec["wrapped_dek"])), "bytes for a 32-byte key")
print("decrypt:", decrypt_record(rec).decode())

# Rotating the KEK: unwrap with the old KEK, wrap with the new one. The bulk ciphertext is untouched.
dek = kms_unwrap("kek-2025", bytes.fromhex(rec["wrapped_dek"]))
rotated = dict(rec, kid="kek-2026", wrapped_dek=kms_wrap("kek-2026", dek).hex())
print("after rotation: ct unchanged:", rotated["ct"] == rec["ct"], " decrypt:", decrypt_record(rotated).decode())

# Copying the ciphertext to another customer's row fails: the AAD (record id) no longer matches.
try:
    decrypt_record(dict(rotated, id="cust-0815"))
except Exception as e:
    print("moved to cust-0815:", type(e).__name__)
stored: {'id': 'cust-4711', 'kid': 'kek-2025', 'wrapped_dek': 'c61a91adb2cef242...', 'nonce': '0000000000000000...', 'ct': 'b87f150bfadc031d...'}
wrapped DEK: 40 bytes for a 32-byte key
decrypt: IBAN XX00 LAB 0000 0000
after rotation: ct unchanged: True  decrypt: IBAN XX00 LAB 0000 0000
moved to cust-0815: InvalidTag

What the pattern gives you:

  • Cheap rotation of the KEK: re-wrap 40-byte DEKs, not terabytes of data. Re-encrypting the data itself (DEK rotation) is a separate, slower job, needed when a DEK may be exposed or a cryptoperiod ends.
  • Access control and audit at the KMS: every unwrap is a logged API call tied to an identity, so "who could read customer 4711's IBAN" has an answer.
  • Crypto-shredding: destroy a KEK (say, one per tenant) in the KMS and every record wrapped under it becomes unreadable, including copies in old backups, which is how many systems implement deletion requests.
  • The key id (kid) in each record tells the reader which KEK version to use, so old and new keys coexist during rotation.

HSMs and KMSs

A hardware security module is a tamper-resistant device that generates and holds keys and performs operations with them, so keys never exist in application memory. FIPS 140-3 (the successor of FIPS 140-2) and Common Criteria certify them; Level 3 adds tamper response and identity-based authentication. Cloud KMSs run HSM fleets behind an API; dedicated cloud HSMs (AWS CloudHSM, Azure Managed HSM) give single-tenant control. Root CA keys, code-signing keys, payment keys and KEKs belong there. Smaller cousins: TPMs in PCs and servers, Secure Enclave and StrongBox on phones, YubiKeys and smart cards.

An HSM protects the key, not its use: an attacker who controls an application with permission to call Decrypt or Sign can still decrypt or sign. In the 2023 Storm-0558 incident, attackers forged authentication tokens with a Microsoft consumer signing key that had left its protected environment and was accepted where it shouldn't have been. How the key was stolen is not settled: Microsoft's 2023 report suggested a crash dump, and in March 2024 it added that no crash dump containing the key had been found. Narrow permissions and monitoring of key use matter as much as the hardware.

How key-management problems are detected

  • Secret scanning of repositories, images, CI logs and tickets for key material (BEGIN PRIVATE KEY, AWS keys, high-entropy strings): gitleaks, trufflehog, GitHub secret scanning (scanning).
  • Inventory: every key, its owner, purpose, algorithm, location, creation date, last rotation and what it protects ("crypto bill of materials"). Keys without an owner are findings.
  • KMS audit logs: unusual callers of Decrypt/Sign, spikes, use from unexpected networks; key policies that grant kms:* to broad roles.
  • Configuration: data keys stored unwrapped next to data, encryption keys in environment variables of many services, one key shared across environments (dev and prod).

How it is fixed

  • Generate keys in the KMS/HSM or with a CSPRNG; store only wrapped keys in applications; keep KEKs non-exportable.
  • One key per purpose and environment; least-privilege key policies; separate the people who administer keys from those who use them.
  • Automatic rotation on a schedule (cloud KMSs offer automatic rotation, often yearly, though it usually has to be turned on), plus a tested emergency rotation procedure.
  • Back up keys (or make the KMS handle redundancy) and test restores; plan destruction.
  • Monitor key use and alert on anomalies.

Pitfalls

  • Rotating a key without re-encrypting data that the old key protected, and then deleting the old key: data loss.
  • "Encrypted at rest" with the key on the same disk: protects against a stolen disk, not against anyone with access to the system.
  • Long-lived static cloud access keys used to reach the KMS: the KMS is only as safe as the credentials that call it. Use workload identity instead.

Practice

1. A team stores database backups encrypted with AES-GCM, and the key in a backup.key file in the same bucket. What do you recommend?

Envelope encryption: a fresh DEK per backup, wrapped by a KEK in the KMS, stored with the backup; the bucket holds only wrapped DEKs. Restrict who may call unwrap, log it, rotate the KEK on a schedule. Rotate the exposed key and re-encrypt existing backups.

2. In the example, why does decryption fail after the record is moved to another customer id?

The record id is the AES-GCM associated data. Changing it changes the expected tag, so the ciphertext only decrypts in its original row.

3. How would you implement "delete all of tenant 42's data" when backups are immutable for seven years?

Give each tenant its own KEK and wrap that tenant's DEKs with it. Deleting the tenant's KEK in the KMS (after its deletion waiting period) makes all its records unreadable everywhere, including in backups.

Test yourself

In envelope encryption, what does the KMS's key (KEK) encrypt?

  1. All the data directly
  2. Only data encryption keys (DEKs)
  3. The TLS traffic
  4. Passwords

Why is rotating a KEK cheap in envelope encryption?

  1. Because keys are short
  2. Only the small wrapped DEKs are re-wrapped; the bulk ciphertext stays
  3. Because the KMS rotates the data
  4. Because AES-GCM allows it

What does an HSM NOT protect against?

  1. Extraction of the key
  2. Physical tampering
  3. An attacker who controls an application allowed to call Sign or Decrypt
  4. Copying the key to a laptop

What is crypto-shredding?

  1. Overwriting disks
  2. Destroying the key so that all data encrypted under it becomes unreadable, including in backups
  3. Shredding paper keys
  4. Compressing ciphertext