Encrypt data locally with a fast per-record DEK (AES-256-GCM), wrap the DEK with a cached tenant KEK, and reserve the HSM strictly for unwrapping KEKs.
TL;DR30-second simplified summary▾
Envelope encryption decouples bulk data encryption (in app/pod RAM) from root-of-trust key wrapping (HSM/KMS), cutting HSM load by 99.9%.
P — The HSM Bandwidth & Blast-Radius Bottleneck.
Direct HSM Crypto vs. Envelope Encryption
An HSM appliance performs 2,000–10,000 crypto ops/sec and requires a network RTT per call. Shipping megabyte payloads to an HSM saturates NICs and stalls every microservice. Conversely, sharing one static AES key across 100M rows violates the AES-GCM 96-bit nonce birthday bound (~2^32 ops) and turns any key leak into a total database compromise.
R & I — Key Wrapping & AAD Context Binding in Python.
Envelope Encryption Pipeline
- Problem
- How do you encrypt 100M records at 100k QPS with hardware-backed root keys?
- Naive Solution
- Call HSM Encrypt() directly for every record payload.
- Why It Fails
- HSM appliances saturate at ~2k-10k ops/sec and add network RTT for every megabyte.
- Alternatives
- Envelope Encryption (HMK -> KEK -> DEK),Direct HSM encryption,Static app-memory AES key
- Engineering Decision
- Use Envelope Encryption with singleflight-cached KEKs (60s TTL) and fresh per-record DEKs.
- Trade-Offs
- Adds ~60 bytes of wrapped_dek + nonces per record, but reduces HSM load by 99.9%.
Why do we pass tenant_id as Additional Authenticated Data (AAD) in AES-256-GCM?
Every ciphertext envelope stores (kek_version, wrapped_dek, nonce, ciphertext_with_tag). Binding tenant_id and kek_version as AAD prevents an attacker with DB write access from copying a ciphertext from Tenant A's row into Tenant B's row:
import os
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
def envelope_encrypt(kek: bytes, tenant_id: str, plaintext: bytes) -> dict:
dek = os.urandom(32) # Fresh 256-bit per-record DEK
aad = tenant_id.encode("utf-8")
dek_nonce = os.urandom(12)
wrapped_dek = AESGCM(kek).encrypt(dek_nonce, dek, aad)
data_nonce = os.urandom(12)
ciphertext = AESGCM(dek).encrypt(data_nonce, plaintext, aad)
return {"wrapped_dek": wrapped_dek, "dek_nonce": dek_nonce, "data_nonce": data_nonce, "ct": ciphertext}
M & E — Lazy DEK Re-Wrapping & When Not to Use It.
KEK Version Lifecycle
When rotating KEK v2 -> v3, a background worker unwraps wrapped_dek with v2 and re-wraps it with v3 without ever touching the multi-megabyte payload. When NOT to use per-record DEKs: Tiny < 32-byte fields (e.g., 16-digit card tokens) where 60 bytes of envelope metadata triples storage; use a single deterministic/epoch DEK with key rotation instead.