Key Management Fundamentals
Encryption is only as strong as key management. This guide covers key lifecycle management for ECM Protocol implementations.
Key Hierarchy
Envelope Encryption
// Three-tier key hierarchy
{
"master_key": {
"location": "HSM",
"purpose": "encrypt_key_encryption_keys",
"rotation": "annual"
},
"key_encryption_key": {
"encrypted_by": "master_key",
"purpose": "encrypt_data_encryption_keys",
"rotation": "quarterly"
},
"data_encryption_key": {
"encrypted_by": "key_encryption_key",
"purpose": "encrypt_context_data",
"rotation": "monthly",
"per_tenant": true
}
}
Key Generation
Secure Generation
class KeyGenerator {
// Use cryptographically secure random
generateKey(algorithm: string): CryptoKey {
switch (algorithm) {
case 'AES-256-GCM':
return crypto.generateKey('AES-GCM', 256);
case 'RSA-4096':
return crypto.generateKeyPair('RSA', {
modulusLength: 4096,
publicExponent: 65537
});
}
}
}
Key Storage
HSM Integration
// Master keys in HSM
{
"key_store": {
"type": "hsm",
"provider": "aws_cloudhsm",
"cluster_id": "cluster-123",
"keys": {
"master_key": {
"handle": "key-abc",
"extractable": false,
"operations": ["wrap", "unwrap"]
}
}
}
}
Key Vault for KEKs/DEKs
// Wrapped keys in vault
class KeyVault {
async storeKey(keyId: string, wrappedKey: Buffer): Promise<void> {
await this.vault.write(\`secret/keys/\${keyId}\`, {
wrapped_key: wrappedKey.toString('base64'),
wrapped_by: 'master_key_v1',
created_at: new Date().toISOString()
});
}
async getKey(keyId: string): Promise<Buffer> {
const secret = await this.vault.read(\`secret/keys/\${keyId}\`);
const wrappedKey = Buffer.from(secret.wrapped_key, 'base64');
return await this.hsm.unwrap('master_key_v1', wrappedKey);
}
}
Key Rotation
Rotation Process
async function rotateDataEncryptionKey(tenantId: string): Promise<void> {
// 1. Generate new key
const newKey = await keyGenerator.generateKey('AES-256-GCM');
const newKeyId = \`dek-\${tenantId}-\${Date.now()}\`;
// 2. Store new key (wrapped)
const wrapped = await hsm.wrap('kek-current', newKey);
await keyVault.storeKey(newKeyId, wrapped);
// 3. Update key reference
await keyRegistry.setCurrentKey(tenantId, newKeyId);
// 4. Re-encrypt existing data (background)
await scheduleReencryption(tenantId, newKeyId);
// 5. Retire old key after re-encryption complete
}
Key Access Control
Permission Model
{
"key_permissions": {
"context-api": {
"keys": ["dek-*"],
"operations": ["decrypt"]
},
"key-rotation-service": {
"keys": ["dek-*", "kek-*"],
"operations": ["encrypt", "decrypt", "rotate"]
},
"security-admin": {
"keys": ["*"],
"operations": ["*"],
"requires_approval": true
}
}
}
Conclusion
Proper key management is essential for context encryption. Implement key hierarchy, use HSMs for master keys, rotate regularly, and audit all key operations.