Secrets-in-DB Pattern: Securely Storing Secrets in Databases
The Secrets-in-DB pattern is a best-practice approach for storing sensitive data (e.g., API keys, passwords, tokens, certificates) directly in a relational or NoSQL database while minimizing exposure risks. It combines envelope encryption for data protection, HSM/KMS for key management, and ciphertext queries for functional querying without decryption. This avoids plaintext storage and reduces reliance on external vaults like HashiCorp Vault or AWS Secrets Manager for every access.
1. Core Components
Component
Purpose
Tools/Examples
Envelope Encryption
Encrypts secrets with a per-secret Data Encryption Key (DEK), then encrypts the DEK with a master Key Encryption Key (KEK). Only the KEK lives outside the DB (in HSM/KMS).
AES-256-GCM for DEK; store {ciphertext, encrypted_DEK, IV, auth_tag} as a blob.
HSM/KMS
Securely generates, rotates, and stores KEKs. Handles key ops without exposing raw keys.
AWS KMS, Google Cloud KMS, Azure Key Vault, YubiHSM, Thales Luna HSM.
Ciphertext Queries
Enables searches/indexes on encrypted data using deterministic encryption or order-preserving schemes.
Deterministic AES (for equality checks), Blind Index (hash-based for lookups).
2. How It Works (Step-by-Step)
code
1. Generate DEK (ephemeral, app-side or KMS-derived).
2. Encrypt secret → ciphertext using DEK + IV.
3. Encrypt DEK → encrypted_DEK using KMS/HSM KEK.
4. Store in DB: `{id, ciphertext, encrypted_DEK, metadata}` (ciphertext is queryable).
5. Retrieve:
- Query on ciphertext/metadata (no decrypt).
- Fetch row → KMS decrypts encrypted_DEK → DEK.
- App decrypts ciphertext → plaintext (in memory only).
6. Rotate: New KEK re-encrypts all DEKs via batch jobs.
Example Schema (PostgreSQL):
sql
CREATE TABLE secrets (
id UUID PRIMARY KEY,
name VARCHAR(255), -- e.g., "api_key_prod"
ciphertext BYTEA NOT NULL, -- Encrypted secret
encrypted_dek BYTEA NOT NULL, -- DEK encrypted by KMS
iv BYTEA NOT NULL, -- Initialization vector
auth_tag BYTEA, -- GCM auth tag
created_at TIMESTAMP,
blind_index BYTEA -- For ciphertext queries (deterministic hash)
);
-- Index for queries
CREATE INDEX idx_blind_name ON secrets(blind_index);
from cryptography.fernet import Fernet
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
import boto3
import hashlib
import os
kms = boto3.client('kms', region_name='us-east-1')
KEY_ID = 'alias/my-keystore' # HSM/KMS KEK alias
def encrypt_secret(secret: str, context: dict = None) -> dict:
# 1. Gen DEK
dek = os.urandom(32)
iv = os.urandom(12)
aesgcm = AESGCM(dek)
ciphertext = aesgcm.encrypt(iv, secret.encode(), None)
# 2. Encrypt DEK with KMS
enc_dek = kms.encrypt(
KeyId=KEY_ID,
Plaintext=dek,
EncryptionContext=context # Binding metadata
)['CiphertextBlob']
# 3. Blind index for queries
blind_idx = hashlib.sha256(secret.lower().encode()).digest()[:16] # Deterministic
return {
'ciphertext': ciphertext,
'encrypted_dek': enc_dek,
'iv': iv,
'blind_index': blind_idx
}
def decrypt_secret(enc_data: dict) -> str:
# Fetch & decrypt DEK
dek_resp = kms.decrypt(CiphertextBlob=enc_data['encrypted_dek'])
dek = dek_resp['Plaintext']
# Decrypt secret
aesgcm = AESGCM(dek)
secret = aesgcm.decrypt(enc_data['iv'], enc_data['ciphertext'], None).decode()
return secret
# Usage
enc = encrypt_secret("sk-abc123")
# Store enc in DB
secret = decrypt_secret(enc) # "sk-abc123"
Ciphertext Query Example:
sql
-- Find secrets by prefix (using blind_index or deterministic encrypt)
SELECT * FROM secrets WHERE blind_index = decode('query_hash', 'hex');
-- Or partial match with order-preserving encryption (e.g., for credit cards).
3. Pros & Cons
Pros
Cons
✅ High performance (DB-native, no vault API calls).
❌ DB breach exposes ciphertexts (mitigate with DB encryption-at-rest + ACLs).
✅ Granular access (row-level security).
❌ Key rotation requires re-encryption jobs.
✅ Queryable without decrypt (e.g., "find all API keys for service X").
Libs: boto3 (AWS), google-cloud-kms, pycryptodome, sqlcipher for DB-side.
This pattern scales to millions of secrets (e.g., at scale in fintech/SaaS). If you need code for a specific DB/KMS or deeper dive (e.g., rotating DEKs), provide more details! 🔍