Envelope Encryption Pattern for PII in Databases
As Sherlock, I'll deduce a robust, production-grade design for protecting PII (e.g., email, SSN, phone) in a database using envelope encryption . This pattern separates data encryption keys (DEKs) from key encryption keys (KEKs) for scalability, compliance (GDPR, HIPAA), and auditability. I'll cover keys, rotation, and search explicitly.
1. Core Concepts
Envelope Encryption : PII is encrypted with a symmetric DEK (e.g., AES-256-GCM). The DEK is wrapped (encrypted) with a KEK and stored alongside the ciphertext.
Why? DEKs can be rotated frequently without KMS round-trips; KEKs stay in a secure KMS (e.g., AWS KMS, GCP KMS, Azure Key Vault, HashiCorp Vault).
DB Assumptions : Relational (Postgres/MySQL) or NoSQL (DynamoDB). Store in columns like encrypted_pii, encrypted_dek, kek_id, version.
Text Diagram: Data Structure in DB
code Copy code
Table: users_pii
| id | tenant_id | pii_field | encrypted_pii (BYTEA) | encrypted_dek (BYTEA) | kek_id | dek_version | blind_index (BYTEA) | created_at |
|----|-----------|-----------|-----------------------|-----------------------|--------|-------------|---------------------|------------|
| 1 | 123 | email | AES-GCM(PII, DEK) | AES-KMS(PII, KEK) | kek-456| 1 | HMAC(PII, search_key)| 2023-... |
2. Key Management
Hierarchical, tenant-isolated keys for multi-tenancy.
Key Hierarchy
code Copy code
Root KEK (KMS-managed, global/region)
├── Tenant KEK (per-tenant, KMS-generated)
└── DEK (per-PII-record/field, app-generated)
KEK (Key Encryption Key) :
256-bit, managed by KMS.
Per-tenant : tenant_kek_v1 (KMS aliases support versioning).
Rotation handled by KMS (automatic key versions).
Never leaves KMS; use Encrypt/Decrypt API calls.
DEK (Data Encryption Key) :
256-bit AES key, generated randomly by app (crypto.randomBytes(32)).
Per-record : Unique DEK per PII row (high security, but more storage).
Alternative : Per-field (e.g., one DEK for all emails in a tenant) for efficiency.
Lifetime: Tied to data; rotate on demand.
Search Key (for blind indexes):
Separate 256-bit HKDF-derived key from Tenant KEK: search_key = HKDF(tenant_kek, "search").
Used only for deterministic hashing (not encryption).
Encryption Flow (Pseudocode)
python Copy code
import kms_client # AWS KMS, etc.
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
import hashlib, hmac
def encrypt_pii(pii: str, tenant_id: str) -> dict:
# 1. Get Tenant KEK (via KMS alias)
kek_id = f"alias/tenant-{tenant_id}-kek"
# 2. Generate fresh DEK
dek = os.urandom(32)
# 3. Encrypt PII with DEK (AEAD for authenticity)
aesgcm = AESGCM(dek)
nonce = os.urandom(12)
ciphertext = aesgcm.encrypt(nonce, pii.encode(), None) # Associated data=None
# 4. Encrypt DEK with KEK (KMS call)
encrypted_dek = kms_client.encrypt(plaintext=dek, key_id=kek_id)
# 5. Blind index for search: HMAC(PII, search_key)
search_key = derive_search_key(tenant_id) # HKDF from Tenant KEK
blind_index = hmac.new(search_key, pii.encode(), hashlib.sha256).digest()
return {
'encrypted_pii': ciphertext,
'encrypted_dek': encrypted_dek['ciphertext'],
'kek_id': kek_id,
'blind_index': blind_index
}
Decryption Flow
python Copy code
def decrypt_pii(encrypted_pii: bytes, encrypted_dek: bytes, kek_id: str) -> str:
# 1. Decrypt DEK with KMS
dek = kms_client.decrypt(ciphertext=encrypted_dek, key_id=kek_id)['plaintext']
# 2. Extract nonce (first 12 bytes) and decrypt
nonce = encrypted_pii[:12]
aesgcm = AESGCM(dek)
pii = aesgcm.decrypt(nonce, encrypted_pii[12:], None).decode()
return pii
3. Key Rotation
Zero-downtime, phased approach. Automate via Lambda/Cron + queue (SQS).
KEK Rotation (KMS-Handled, Quarterly)
KMS creates new version (kek_v2).
Update app config to use new alias pointing to v2.
Lazy re-encryption : Old encrypted_dek (with v1) still decrypts via KMS versioning.
Background job: For active data, decrypt DEK with old KEK → re-encrypt with new → update DB.
Purge old KEK version after 90 days (compliance window).
DEK Rotation (Per-Record, Monthly or on Access)
Trigger : Cron job per-tenant, or on high-risk access (e.g., anomaly detection).
Process (idempotent):
python Copy code
def rotate_dek(row_id: int, tenant_id: str):
row = db.get(row_id)
pii = decrypt_pii(...) # Using current keys
new_encrypted = encrypt_pii(pii, tenant_id) # Fresh DEK
new_encrypted['dek_version'] += 1
db.update(row_id, new_encrypted)
Batch : Use queues; process 1% of data/day. Track dek_version > threshold for prioritization.
Fallback : Dual-DEK storage temporarily (old + new) during transition.
Audit : Log all rotations to CloudTrail/Splunk.
Cost/Perf : KMS calls ~$0.03/10k; DEK ops are local (fast).
4. Search on Encrypted PII
Full decryption scans are inefficient/expensive. Use Blind Indexing (deterministic, but blinded).
Blind Index Pattern
How : blind_index = HMAC-SHA256(PII || salt, search_key) (salt = tenant_id + field_type).
Storage : Fixed-size (32 bytes), indexed column.
Query :
sql Copy code
SELECT * FROM users_pii
WHERE tenant_id = 123
AND blind_index = HMAC('bob@example.com', search_key);
Security :
Collision-resistant (SHA256).
No plaintext leakage (even DBAs can't reverse).
Frequency analysis mitigated by per-tenant search_key + salting.
Limits: Exact-match only (no LIKE/wildcards). For fuzzy: Use n-gram blind indexes.
Advanced Options
Use Case Technique Tradeoffs Exact Match Blind Index (HMAC) Fast, secure Prefix Search Blind Index on substr(PII,1,3) More indexes (+storage) Range (e.g., age) Order-Preserving Encryption (OPE) on numeric PII Complex impl., vuln. to sorting attacks Full-Text External service (e.g., Elasticsearch with tokenization) Offload, higher latency
Implementation Tip : Cache search_key in app (rotate with KEK). Use bytes_to_string(blind_index) for DB indexing.
5. Best Practices & Gotchas
Compliance : Use FIPS-140-2 KMS. Envelope enables key escrow (share KEK).
Perf : DEK ops <1ms local; KMS ~50ms (batch for bulk).
Backup : Encrypt DB backups with separate DEK.
Threat Model : Protects against DB breaches (no plaintext/DEK). Insider threat: KMS logs all access.
Monitoring : Alert on rotation failures, decrypt errors (>1%).
Libs : Python cryptography, Node aws-sdk. Avoid CryptoJS.
This pattern scales to millions of rows (e.g., used at scale by Auth0/Okta). If you provide DB/vendor details, I can refine further. Elementary, my dear user! 🔍