cryptography-key-management

Comprehensive cryptographic key lifecycle management, KMS integration, and compliance

Cryptographic Key Management

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

When to Use This Skill

Activate this skill when:

Core Concepts

Key Management Lifecycle

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.

Key Hierarchies

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:


Key Generation

Cryptographically Secure Random Number Generators (CSRNGs)

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:

Key Derivation Functions (KDFs)

For 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
)

Key Storage

Storage Tiers

| 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 |

Hardware Security Module (HSM)

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:

Cloud KMS Platforms

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:..."

Key Rotation

Why Rotate Keys?

Reasons:

  1. Limit blast radius of compromise
  2. Compliance requirements (PCI-DSS, HIPAA)
  3. Cryptographic hygiene (reduce ciphertext under single key)
  4. Mitigate key exposure (employee departure, system compromise)

Rotation Frequency:

Rotation Strategies

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>

Access Control

Principle of Least Privilege

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"
      }
    }
  }]
}

Compliance Standards

PCI-DSS Requirements

Requirement 3.6: Protect cryptographic keys

HIPAA Requirements

Security Rule § 164.312(a)(2)(iv): Encryption and decryption (addressable)

GDPR Requirements

Article 32: Security of processing

FIPS 140-2 Requirements

Approved Algorithms:

❌ Not Approved:


Best Practices

Key Management Checklist

Generation:

Distribution:

Storage:

Rotation:

Destruction:

Access Control:

Monitoring:


Anti-Patterns

❌ Never do:


Level 3: Resources

Reference Materials

Comprehensive Documentation:

Production Scripts

Three executable scripts (all with --help and --json support):

  1. scripts/audit_keys.py (848 lines)
  1. scripts/rotate_master_keys.py (821 lines)
  1. scripts/generate_key_hierarchy.py (698 lines)

Production Examples

Five production-ready examples:

  1. examples/aws_kms_integration.py
  1. examples/hashicorp_vault_setup.py
  1. examples/key_rotation_automation.py
  1. examples/secrets_management.py
  1. examples/compliance_config.py

Usage

Run 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)

Quick Reference

Common Commands

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

Related Skills


Resources

Standards and Specifications

Compliance Resources

Tools and Libraries