StackPractices
intermediate By Mathias Paulenko

Encryption Key Lifecycle Template

A template for managing the creation, distribution, rotation, and destruction of encryption keys across applications and services.

Overview

A leaked key that nobody revokes is worse than no encryption at all: it gives a false sense of safety while the data stays readable to whoever holds the key. Most real-world key failures aren’t broken algorithms — they’re keys hardcoded in repositories, never rotated, shared across environments, or left active months after the service that used them was retired.

This template gives you a working policy for the full lifecycle: how keys are classified, who owns each stage, when rotation happens, who can do what, and how compromise and destruction are handled. Fill in the tables with your own values and you get a document your security team can enforce and your auditors can read.

For the hands-on procedure of rotating a specific key with zero downtime, use the companion Encryption Key Rotation Runbook. For implementing encryption at rest in an application, see the encryption at rest recipe.

When to Use

  • Designing a key management strategy for a new application or platform.
  • Selecting or configuring a key management service (KMS) or hardware security module (HSM).
  • Establishing a key rotation policy to satisfy PCI DSS, SOC 2, or internal risk requirements.
  • Responding to a key compromise or suspected unauthorized key access.
  • Offboarding a system or retiring a service that holds encrypted data.
  • Preparing evidence for a security audit that asks how keys are governed.

Don’t use this template as a substitute for a secrets manager policy. API tokens, passwords, and connection strings follow a different lifecycle — the Secret Rotation Schedule Template covers that case.

Prerequisites

  • A key management service such as AWS KMS, Azure Key Vault, Google Cloud KMS, or HashiCorp Vault, or an HSM for keys that must never leave hardware.
  • A data classification that says which data needs encryption at rest, in transit, or in use.
  • An inventory of systems that generate or consume encryption keys.
  • Named roles for key custodians, key users, and auditors. These can be the same teams you already have; what matters is that the duties are separated.

Template

1. Key Classification

Key TypePurposeExampleProtection Level
Data encryption key (DEK)Encrypts data at restAES-256 database keyHigh
Key encryption key (KEK)Encrypts DEKsRSA or AES key in KMSCritical
Transport keyEncrypts data in transitTLS private keyHigh
Signing keySigns code or artifactsECDSA code signing keyCritical
API keyAuthenticates API callsHMAC secretMedium
Backup keyEncrypts backupsAES-256 backup keyHigh

2. Key Lifecycle Stages

StageActivitiesOwnerArtifacts
GenerationCreate key with approved algorithm and lengthPlatform teamKey metadata, algorithm
DistributionSecurely deliver key to authorized systemsSecurity teamAccess log, key alias
StorageStore in KMS, HSM, or vaultPlatform teamKey location, policy
UsageEnforce least privilege and audit all operationsApplication teamAccess policy, audit logs
RotationReplace key periodically or after incidentSecurity teamRotation schedule, new key
CompromiseRevoke, rotate, and assess impactSecurity teamIncident report, new key
DestructionSecurely delete key when no longer neededPlatform teamDestruction certificate
ArchiveRetain key metadata for compliance without key materialCompliance teamRetention record
flowchart diagram: Generation

3. Key Rotation Policy

Key TypeRotation FrequencyTriggerAutomatic
KEK / KMS key1 yearScheduledYes
TLS certificate key90 days–1 yearCertificate expiryYes
Database DEK1 yearScheduledNo, planned maintenance
Signing key1 yearScheduled or suspected compromiseSemi-automatic
API HMAC secret90 daysScheduled or credential leakYes
Backup key1 yearScheduledNo

NIST SP 800-57 calls these windows cryptoperiods: the shorter the window, the less data a leaked key exposes. Automatic rotation is safe for KMS-managed keys because the service keeps old key material for decryption — you’re rotating the key, not re-encrypting the world on a schedule.

4. Access Control Matrix

RoleGenerateUseRotateDestroyAudit
Application serviceNoYesNoNoNo
Platform engineerYesNoYesNoYes
Security engineerNoNoYesNoYes
Key custodianYesNoYesNoYes
AuditorNoNoNoNoYes
Compliance officerNoNoNoYes with approvalYes

Two rules hold this matrix together. Applications use keys but never manage them, and no single person can both operate a key and approve its destruction. If your team is small, merge platform engineer and key custodian into one role but keep the destroy-approval separate.

5. Key Inventory and Ownership

Every key lives in one registry. A key that isn’t in the registry doesn’t get rotated, doesn’t get destroyed on schedule, and will surprise you during an incident.

FieldExampleNotes
Key ID / aliasalias/payments-dekStable alias, not a rotating ARN
TypeDEKFrom the classification table
Ownerpayments-platform@Team, not a person
PurposeEncrypts card vault columnOne line, plain language
Systemspayments-api, vault-replicaEvery consumer
AlgorithmAES-256-GCMInclude mode
Created2026-01-15From KMS metadata
Rotation due2027-01-15Drives the schedule
Custodiansec-eng on callApproves destroy
Statusactiveactive / rotating / compromised / pending-deletion

6. Compromise Response Procedure

StepActionOwnerTimeline
1Revoke or disable the compromised keySecurity teamWithin 1 hour
2Identify all systems and data protected by the keySecurity teamWithin 4 hours
3Rotate to a new key and re-encrypt dataPlatform teamWithin 24 hours
4Notify stakeholders and customers if requiredIncident commanderWithin 24 hours
5Preserve audit logs and evidenceSecurity teamImmediate
6Update incident report and lessons learnedSecurity teamWithin 1 week

7. Destruction Checklist

  • Key is no longer used by any application or service.
  • Encrypted data has been decrypted with the new key or securely deleted.
  • All backups and replicas containing the key are identified.
  • Key material is deleted from KMS, HSM, or vault.
  • Destruction is logged and signed by key custodian and compliance officer.
  • Retention period for metadata is documented and enforced.

Where the KMS supports it, use scheduled deletion (7–30 day pending window) instead of immediate deletion. The window is your undo button when a forgotten consumer turns up on day three.

8. Key Backup and Recovery

KEKs and HSM-resident keys need their own recovery plan, because losing them is equivalent to losing every piece of data they protect.

  • Back up KEK material or its wrapping keys in a second region or a second HSM partition, under the same access controls as the primary.
  • Document the HSM failover procedure and test it quarterly. HSM availability becomes the availability of every service that depends on its keys.
  • Test key recovery once a year with a real restore, not a checklist read-through. A key that can’t be recovered when needed causes data loss as severe as a breach.
  • Record who holds each recovery share and where shares are stored. Split knowledge (m-of-n) beats a single sealed envelope.

9. Program Metrics

Track a few numbers so the policy stays alive after the document is written.

MetricTargetSource
Keys with automatic rotation enabled≥ 90% of eligibleKMS inventory
Keys past their rotation due date0Key registry
Mean time to revoke on compromise< 1 hourIncident reports
Orphaned keys (no owner, no consumer)0Quarterly inventory audit
Hardcoded key findings in repos0Secret scanning
Recovery test performedAnnualTest log

10. Compliance Mapping

Use this table when an auditor asks where each requirement lives.

FrameworkRequirementWhere this template covers it
NIST SP 800-57 Part 1Cryptoperiods, key statesSections 2–3
PCI DSS 3.5–3.7Key generation, storage, rotation, destructionSections 1–7
ISO/IEC 27001 (A.8.24)Cryptographic key managementWhole document
SOC 2 (CC6.1, CC6.7)Logical access, encryption of data at rest/in transitSections 4, 6
GDPR Art. 32 / Art. 17Protection measures, erasure via crypto-shreddingSections 7–8

Explanation

Encryption is only as strong as the keys that protect it, and most of that strength comes from boring operational discipline. The template works because it makes ownership explicit at every stage: a key always has a team that generates it, a smaller set of roles that may touch it, a date by which it must rotate, and a signed trail when it dies.

Two design choices are worth a second thought. First, separating DEKs from KEKs (envelope encryption) is what makes rotation cheap: you re-wrap a small DEK instead of re-encrypting terabytes of data. Second, automatic rotation trades a little control for a large drop in human error — enable it everywhere the KMS supports it and reserve manual rotation for the cases that genuinely need a maintenance window.

Centralizing on one KMS also has a cost: it concentrates risk and makes IAM policy the real security boundary. Keep the key policies tight, log every administrative action, and treat access to the KMS as higher privilege than access to the data itself.

AWS KMS Key Rotation Policy

# AWS KMS key with automatic rotation
Resources:
  EncryptionKey:
    Type: AWS::KMS::Key
    Properties:
      Description: Application data encryption key
      EnableKeyRotation: true
      KeyPolicy:
        Version: '2012-10-17'
        Statement:
          - Effect: Allow
            Principal:
              AWS: !Sub 'arn:aws:iam::${AWS::AccountId}:role/app-role'
            Action:
              - kms:Encrypt
              - kms:Decrypt
              - kms:ReEncrypt*
              - kms:GenerateDataKey*
              - kms:DescribeKey
            Resource: '*'
          - Effect: Allow
            Principal:
              AWS: !Sub 'arn:aws:iam::${AWS::AccountId}:root'
            Action:
              - kms:CreateAlias
              - kms:DeleteAlias
              - kms:UpdateAlias
              - kms:ScheduleKeyDeletion
              - kms:EnableKeyRotation
            Resource: '*'
      PendingWindowInDays: 30

Key Rotation Audit Script

#!/bin/bash
# Check and report key rotation status across AWS KMS
set -euo pipefail

REGION="us-east-1"
ALERT_DAYS=7

for key_id in $(aws kms list-keys --region $REGION --query 'Keys[*].KeyId' --output text); do
  rotation_status=$(aws kms get-key-rotation-status --key-id $key_id --region $REGION --query 'KeyRotationEnabled' --output text 2>/dev/null || echo "N/A")
  key_desc=$(aws kms describe-key --key-id $key_id --region $REGION --query 'KeyMetadata.Description' --output text 2>/dev/null || echo "N/A")
  creation_date=$(aws kms describe-key --key-id $key_id --region $REGION --query 'KeyMetadata.CreationDate' --output text 2>/dev/null || echo "N/A")

  echo "Key: $key_id | Description: $key_desc | Rotation: $rotation_status | Created: $creation_date"

  if [ "$rotation_status" = "False" ]; then
    echo "WARNING: Key $key_id does not have automatic rotation enabled"
  fi
done

Key Compromise Response Runbook

=== Key Compromise Response ===

1. CONTAIN (immediate, 0-15 min)
   - Disable the compromised key in KMS/HSM
   - Revoke all access policies for the key
   - Identify all data encrypted with the compromised key

2. ASSESS (15-60 min)
   - Determine scope: which services, databases, backups affected
   - Check access logs for unauthorized key usage
   - Notify security team and key custodian

3. REPLACE (1-4 hours)
   - Create new key with same policy
   - Re-encrypt all affected data with new key
   - Update application configurations to use new key ARN/ID
   - Deploy updated configurations

4. DESTROY (after verification)
   - Schedule deletion of compromised key
   - Verify all data uses new key
   - Document incident and update key inventory

5. POST-INCIDENT (within 1 week)
   - Review root cause of compromise
   - Update access policies and monitoring
   - Conduct full key inventory audit
   - Update key lifecycle documentation

Variants

  • Cloud KMS key lifecycle: uses AWS KMS, Azure Key Vault, or Google Cloud KMS with automatic rotation and IAM policies.
  • HSM-backed key lifecycle: adds physical or cloud HSM protection for keys that need FIPS 140-2 Level 3 or higher.
  • Application-level key lifecycle: focuses on keys generated and managed inside a single application or service.
  • Database encryption key lifecycle: covers transparent data encryption (TDE) and column-level keys.
  • Backup encryption key lifecycle: keeps long-term keys recoverable for archive retention while still protecting them.

What Works

  • Use a centralized KMS or HSM instead of storing keys in application code or config files.
  • Separate data encryption keys from key encryption keys so rotation stays cheap.
  • Rotate keys automatically wherever the service supports it; write down the exceptions.
  • Log every key use and every administrative action, and alert on the administrative ones.
  • Keep keys non-extractable unless an approved process requires export.
  • Rehearse rotation and destruction before an incident forces you to learn them live.
  • Maintain the key inventory from section 5 and audit it quarterly against what the KMS actually reports.
  • Require a second person’s approval for destruction and for any policy change on a KEK.

Common Mistakes

  • Hardcoding keys in source code or configuration files, including “temporary” ones that ship.
  • Never rotating keys because nothing has caught fire yet.
  • Sharing one key across several applications or environments, which turns one leak into several breaches.
  • Allowing key export without approval or audit trail.
  • Deleting a key before confirming that backups and replicas no longer reference it.
  • Treating the compromise runbook as optional reading until the day it’s needed.
  • Letting rotated-out keys stay active “just in case” instead of scheduling their destruction.

Troubleshooting

  • Rotation is enabled but apps still use old key material: the application pins a key ARN or caches the DEK in memory. Point consumers at the alias, not the key ID, and restart long-lived services after rotation so they pick up new material.
  • Re-encryption jobs stall or get throttled: mass Decrypt + Encrypt against KMS hits API rate limits. Batch the work, add exponential backoff, and consider envelope encryption so only DEKs move.
  • BYOK import fails: the wrapping algorithm or key spec doesn’t match what the cloud KMS expects (for AWS: RSAES-OAEP with SHA-256 and a 256-bit AES key). Check GetParametersForImport output instead of guessing parameters.
  • A key was deleted and something broke: if the KMS used scheduled deletion, recover it inside the pending window (CancelKeyDeletion in AWS, az keyvault key recover in Azure). After the window, restore from the KEK backup — this is why section 8 exists.
  • Orphaned keys keep accumulating: aliases get renamed, services get retired, and keys stay billable. Run the audit script monthly, tag each orphan’s last-used date, and schedule deletion after 30 days of zero usage.
  • Destruction request blocked by compliance: the metadata archive (section 2, last row) is missing. Retain key metadata, not key material — auditors need the record that the key existed and was destroyed correctly.

Further Reading

Frequently Asked Questions

What is the difference between a DEK and a KEK?

A data encryption key (DEK) encrypts the actual data. A key encryption key (KEK) encrypts the DEK, so the DEK can be stored next to the data while the KEK stays in a secure KMS or HSM.

Should we rotate keys even if there is no compromise?

Yes. Scheduled rotation shrinks the window in which an undetected leak stays useful, and most compliance frameworks require it anyway.

How do we rotate a key that protects a large database?

Use a two-key rotation: introduce the new key, re-encrypt data gradually or lazily on access, then retire the old key once everything reads through the new one.

What is envelope encryption and why should we use it?

Envelope encryption encrypts each DEK with a KEK. The DEK encrypts data and travels with it; the KEK never leaves the KMS. Rotating the KEK only re-wraps the small DEKs instead of the whole dataset, and access control is centralized at the KEK.

How do we manage keys across multiple cloud providers?

Use a cloud-agnostic KMS such as HashiCorp Vault's Transit engine, or keep a separate KMS per cloud with one centralized key inventory. Never copy key material between providers unless you run a BYOK import backed by an HSM.

What is BYOK and when should we use it?

BYOK (Bring Your Own Key) lets you generate key material in your own HSM and import it into a cloud KMS. Use it when compliance requires the material to stay under your control or when you need the same key in two providers. Verify the KMS supports deletion with proof, and protect the import with a proper wrapping key.

How do we audit key usage?

Enable KMS access logging (AWS CloudTrail KMS events, Azure Key Vault diagnostics, GCP Cloud Audit Logs). Log every Encrypt, Decrypt, GenerateDataKey, and admin call, ship them to a SIEM, and alert on anomalies like decrypt calls from new IPs or deletions without approval.

What is crypto-shredding?

Crypto-shredding destroys data by destroying its key: once the key is gone, the ciphertext is unrecoverable. It satisfies erasure requests (GDPR Art. 17) without touching backups. Use per-tenant keys so one deletion affects one tenant's data only.

How do we handle key rotation for TLS certificates?

TLS rotation runs through your certificate system. Managed certs (ACM, cert-manager) renew automatically; self-managed certs need a new key pair, a CSR, and a dual-certificate deploy during the transition so old and new chains both validate.

What is HSM and when do we need it?

An HSM is tamper-resistant hardware that generates and stores keys so the material never leaves the device. You need one when compliance requires FIPS 140-2 Level 3+, when keys must not exist in server memory, or for high-throughput signing. Cloud options include AWS CloudHSM, Azure Dedicated HSM, and Google Cloud HSM — see section 8 for the failover and recovery duties that come with them.