Comprehensive cryptographic key lifecycle management, KMS integration, and compliance
Scope: Key lifecycle (generation, distribution, storage, rotation, destruction), KMS platforms (AWS KMS, GCP KMS, Azure Key Vault, external secret manager), HSM integration, compliance (FIPS 140-2, PCI-DSS, HIPAA, GDPR) Lines: ~500 Last Updated: 2025-10-27
Activate this skill when:
Five Phases:
1. Generation → 2. Distribution → 3. Storage → 4. Rotation → 5. Destruction
↑ │
└──────────────────────────────────────────────────────────────┘
(Cycle repeats)
Critical Principle: The security of encrypted data depends entirely on the security of the encryption keys.
Three-Tier Model (Recommended):
┌─────────────────────────────────────────────┐
│ Level 1: Root Key (Master Key) │ ← Stored in HSM
│ - Rarely rotated (annually or never) │ ← Rarely used
│ - Encrypts KEKs only │ ← FIPS 140-2 Level 3+
└───────────────────┬─────────────────────────┘
│ Encrypts
▼
┌─────────────────────────────────────────────┐
│ Level 2: Key Encryption Key (KEK) │ ← Stored in KMS
│ - Rotated periodically (quarterly/annually) │ ← Encrypts DEKs
│ - One KEK per application/tenant │
└───────────────────┬─────────────────────────┘
│ Encrypts
▼
┌─────────────────────────────────────────────┐
│ Level 3: Data Encryption Key (DEK) │ ← Stored encrypted with data
│ - Rotated frequently (per file/record) │ ← Encrypts actual data
│ - One DEK per file/record/tenant │
└───────────────────┬─────────────────────────┘
│ Encrypts
▼
┌──────────────────┐
│ Encrypted Data │
└──────────────────┘
Benefits:
Platform Sources:
| Platform | CSRNG | Entropy Source | |----------|-------|----------------| | Linux | /dev/urandom | Kernel CSPRNG (hardware RNG, interrupts, disk I/O) | | macOS | /dev/random | Yarrow algorithm | | Windows | CryptGenRandom | Windows CryptoAPI | | AWS KMS | GenerateDataKey | FIPS 140-2 validated | | GCP KMS | GenerateRandomBytes | Cloud HSM |
Python Example:
import os
import secrets
# Generate 256-bit AES key
key = os.urandom(32) # 32 bytes = 256 bits
# Or use secrets module (Python 3.6+)
key = secrets.token_bytes(32)
hex_key = secrets.token_hex(32) # 64 hex characters
❌ Never use:
random.random() (Python) - PredictableMath.random() (JavaScript) - PredictableFor deriving keys from passwords:
| KDF | Standard | Security | Use Case | |-----|----------|----------|----------| | Argon2id | RFC 9106 | Highest (memory-hard) | Password hashing, key derivation (recommended) | | scrypt | RFC 7914 | High (memory-hard) | Key derivation from passwords | | PBKDF2 | RFC 8018 | Moderate | FIPS compliance, legacy systems | | HKDF | RFC 5869 | High | Key derivation from shared secrets (not passwords) |
Argon2id Example:
from argon2 import PasswordHasher
from argon2.low_level import hash_secret_raw, Type
import secrets
password = b"user-password"
salt = secrets.token_bytes(16)
# Derive 256-bit key
key = hash_secret_raw(
secret=password,
salt=salt,
time_cost=3, # Iterations
memory_cost=65536, # 64 MB
parallelism=4, # 4 threads
hash_len=32, # 256-bit key
type=Type.ID # Argon2id
)
| Tier | Security | Cost | Use Case | |------|----------|------|----------| | Tier 1: HSM | Highest (FIPS 140-2 Level 3/4) | $$$$ | Root keys, CA keys | | Tier 2: Cloud KMS | High (FIPS 140-2 Level 2/3) | $$ | Application keys, KEKs | | Tier 3: Encrypted DB | Moderate | $ | Encrypted DEKs | | Tier 4: OS Keystore | Moderate | $ | Local development | | Tier 5: Plaintext | ❌ Never | N/A | N/A |
FIPS 140-2 Levels:
| Level | Requirements | Use Case | |-------|-------------|----------| | Level 1 | Software only | Basic applications | | Level 2 | Tamper-evident seals, role-based auth | Enterprise | | Level 3 | Tamper-resistant hardware, identity-based auth | Financial, healthcare (recommended) | | Level 4 | Environmental protection (voltage, temp) | Government, military |
HSM Vendors:
AWS KMS:
import boto3
kms = boto3.client('kms')
# Create key
response = kms.create_key(Description='App encryption key')
key_id = response['KeyMetadata']['KeyId']
# Enable automatic rotation
kms.enable_key_rotation(KeyId=key_id)
# Encrypt data
ciphertext = kms.encrypt(KeyId=key_id, Plaintext=b'Secret data')
# Decrypt
plaintext = kms.decrypt(CiphertextBlob=ciphertext['CiphertextBlob'])
external secret manager:
# Enable transit engine
vault secrets enable transit
# Create encryption key
vault write -f transit/keys/my-key
# Encrypt
vault write transit/encrypt/my-key plaintext=$(echo "Secret data" | base64)
# Decrypt
vault write transit/decrypt/my-key ciphertext="vault:v1:..."
Reasons:
Rotation Frequency:
Strategy 1: Envelope Encryption (Zero-Downtime)
Re-encrypt KEKs with new root key, DEKs with new KEK. Data stays encrypted with DEKs (no change).
Strategy 2: Versioned Keys (Multi-Version)
Keep old and new keys active. Write new data with new key, read old data with old key. Background job gradually re-encrypts.
AWS KMS Automatic Rotation:
# Enable automatic rotation (annual)
aws kms enable-key-rotation --key-id <key-id>
# Check rotation status
aws kms get-key-rotation-status --key-id <key-id>
Best Practices:
AWS KMS IAM Policy Example:
{
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Action": ["kms:Decrypt", "kms:GenerateDataKey"],
"Resource": "arn:aws:kms:us-east-1:123456789012:key/*",
"Condition": {
"StringEquals": {
"kms:EncryptionContext:Department": "Finance"
}
}
}]
}
Requirement 3.6: Protect cryptographic keys
Security Rule § 164.312(a)(2)(iv): Encryption and decryption (addressable)
Article 32: Security of processing
Approved Algorithms:
❌ Not Approved:
✅ Generation:
✅ Distribution:
✅ Storage:
✅ Rotation:
✅ Destruction:
✅ Access Control:
✅ Monitoring:
❌ Never do:
Comprehensive Documentation:
resources/REFERENCE.md - 2,000+ line technical reference covering:Three executable scripts (all with --help and --json support):
scripts/audit_keys.py (848 lines)scripts/rotate_master_keys.py (821 lines)scripts/generate_key_hierarchy.py (698 lines)Five production-ready examples:
examples/aws_kms_integration.pyexamples/hashicorp_vault_setup.pyexamples/key_rotation_automation.pyexamples/secrets_management.pyexamples/compliance_config.pyRun scripts:
# Audit all keys in AWS KMS
./scripts/audit_keys.py --platform aws-kms --region us-east-1 --json
# Rotate master key
./scripts/rotate_master_keys.py --platform aws-kms --key-id alias/master-key
# Generate 3-tier key hierarchy
./scripts/generate_key_hierarchy.py --tiers 3 --dek-count 100 --visualize
Integrate examples:
# Use AWS KMS integration
from examples.aws_kms_integration import AWSKMSKeyManager
manager = AWSKMSKeyManager(region='us-east-1')
envelope = manager.encrypt_with_envelope(plaintext, 'alias/my-key')
decrypted = manager.decrypt_with_envelope(envelope)
AWS KMS:
# Create key
aws kms create-key --description "App key"
# Enable rotation
aws kms enable-key-rotation --key-id <key-id>
# Encrypt
aws kms encrypt --key-id alias/my-key --plaintext fileb://secret.txt
# Decrypt
aws kms decrypt --ciphertext-blob fileb://encrypted.bin
external secret manager:
# Enable transit
vault secrets enable transit
# Create key
vault write -f transit/keys/my-key
# Encrypt
vault write transit/encrypt/my-key plaintext=$(base64 <<< "secret")
# Rotate
vault write -f transit/keys/my-key/rotate
Google Cloud KMS:
# Create key ring
gcloud kms keyrings create my-keyring --location global
# Create key
gcloud kms keys create my-key --location global --keyring my-keyring --purpose encryption
# Encrypt
gcloud kms encrypt --location global --keyring my-keyring --key my-key --plaintext-file secret.txt --ciphertext-file encrypted.bin