Key Management Best Practices
Key Management Best Practices
Effective key management determines encryption security more than algorithm choice. Poor key management practices undermine even the strongest encryption, making key lifecycle management critical for maintaining data protection. Implementing comprehensive key management requires addressing generation, storage, distribution, rotation, and destruction.
Implement Windows DPAPI for application key protection:
# Protect sensitive data with DPAPI
Add-Type -AssemblyName System.Security
$PlainText = "SensitiveAPIKey123"
$PlainBytes = [System.Text.Encoding]::UTF8.GetBytes($PlainText)
# Encrypt with user scope
$ProtectedBytes = [System.Security.Cryptography.ProtectedData]::Protect(
$PlainBytes,
$null,
[System.Security.Cryptography.DataProtectionScope]::CurrentUser
)
# Save encrypted data
[System.IO.File]::WriteAllBytes("protected.dat", $ProtectedBytes)
# Decrypt when needed
$EncryptedBytes = [System.IO.File]::ReadAllBytes("protected.dat")
$DecryptedBytes = [System.Security.Cryptography.ProtectedData]::Unprotect(
$EncryptedBytes,
$null,
[System.Security.Cryptography.DataProtectionScope]::CurrentUser
)
$DecryptedText = [System.Text.Encoding]::UTF8.GetString($DecryptedBytes)
Linux key management with kernel keyring:
# Add key to kernel keyring
keyctl add user mykey "SecretKeyData" @u
# List keys
keyctl list @u
# Use key in application
KEY_ID=$(keyctl search @u user mykey)
KEY_DATA=$(keyctl print $KEY_ID)
# Set key timeout
keyctl timeout $KEY_ID 3600 # Expire after 1 hour
# Implement key rotation script
#!/bin/bash
OLD_KEY_ID=$(keyctl search @u user app_key 2>/dev/null)
NEW_KEY=$(openssl rand -base64 32)
# Add new key
NEW_KEY_ID=$(keyctl add user app_key_new "$NEW_KEY" @u)
# Update applications to use new key
# ... application-specific logic ...
# Remove old key after transition
if [ -n "$OLD_KEY_ID" ]; then
keyctl unlink $OLD_KEY_ID @u
fi
# Rename new key
keyctl update $NEW_KEY_ID app_key
Hardware Security Module (HSM) integration:
#!/usr/bin/env python3
# Example HSM integration using PKCS#11
import PyKCS11
# Initialize PKCS#11 library
pkcs11 = PyKCS11.PyKCS11Lib()
pkcs11.load('/usr/lib/softhsm/libsofthsm2.so')
# Open session
slot = pkcs11.getSlotList(tokenPresent=True)[0]
session = pkcs11.openSession(slot, PyKCS11.CKF_SERIAL_SESSION | PyKCS11.CKF_RW_SESSION)
session.login('HSMUserPIN')
# Generate key in HSM
key_template = [
(PyKCS11.CKA_CLASS, PyKCS11.CKO_SECRET_KEY),
(PyKCS11.CKA_KEY_TYPE, PyKCS11.CKK_AES),
(PyKCS11.CKA_VALUE_LEN, 32),
(PyKCS11.CKA_TOKEN, True),
(PyKCS11.CKA_PRIVATE, True),
(PyKCS11.CKA_ENCRYPT, True),
(PyKCS11.CKA_DECRYPT, True),
(PyKCS11.CKA_LABEL, "AppEncryptionKey")
]
key_handle = session.generateKey(key_template)
# Use key for encryption (key never leaves HSM)
mechanism = PyKCS11.Mechanism(PyKCS11.CKM_AES_CBC_PAD, "0" * 16)
cipher_text = session.encrypt(key_handle, "Sensitive data", mechanism)