How to Rotate Secrets with a KMS
Manage encryption keys and application secrets so rotation happens on schedule without downtime or redeploys.
On this page
Introduction
A secret that never changes is a secret that grows more dangerous with every day it exists. Rotation limits the window in which a leaked credential is useful, but doing it by hand is error-prone and usually deferred. A key management service provides the primitives to rotate without downtime: keys that can be re-wrapped, envelope encryption that separates the data key from the master key, and versioned keys that let old data stay readable while new data uses the new key. This article explains envelope encryption, rotation strategies for data keys versus application secrets, and how to roll a new secret out so no request fails during the change.
Keys Versus Secrets and Why Rotation Matters
Distinguish encryption keys from credentials. An encryption key transforms data and is never sent to the other party; a credential authenticates. Both benefit from rotation, but the mechanics differ. Rotating an encryption key means re-wrapping or re-encrypting data; rotating a credential means both sides adopt a new value over a short overlap.
Rotation matters because the damage from a leak is proportional to its useful lifetime. A credential rotated every hour has an hour of exposure; one rotated never has years. Rotation also forces the practice of automating propagation, which is what makes recovery from a compromise fast rather than a scramble.
Envelope Encryption
Envelope encryption encrypts data with a data key, then encrypts the data key with a master key held in the KMS. The KMS never exposes the master key; you ask it to decrypt the wrapped data key when you need to read data, and the plaintext data key exists only briefly. The advantage is that rotating the master key requires re-wrapping only the small data keys, not re-encrypting all the data.
import boto3
kms = boto3.client('kms')
def encrypt(plaintext: bytes, master_key_id: str) -> dict:
# Generate a data key; the plaintext copy is used once, then discarded.
data_key = kms.generate_data_key(KeyId=master_key_id, KeySpec='AES_256')
plaintext_key, wrapped_key = data_key['Plaintext'], data_key['CiphertextBlob']
# (AES-GCM encryption with plaintext_key is elided here.)
return {'ciphertext': b'...', 'wrapped_key': wrapped_key, 'key_id': master_key_id}
def decrypt(blob: dict) -> bytes:
# Unwrap the data key using the master key that wrapped it.
plaintext_key = kms.decrypt(
CiphertextBlob=blob['wrapped_key'],
KeyId=blob['key_id'],
)['Plaintext']
# (AES-GCM decryption with plaintext_key is elided here.)
return b'...'
Rotating a Master Key
Most KMS services support automatic rotation of a master key, which creates a new backing key version on a schedule while keeping the old versions available for decryption. This is transparent: existing ciphertext keeps decrypting because the service tracks which version wrapped it, and new encryptions use the newest version. It rotates the key material without changing the key id you reference.
Re-encrypting all data is rarely necessary with versioned keys, because decryption continues to work. If your threat model requires that old ciphertext no longer be decryptable by the old version, you must re-encrypt and then disable the old version, which is a migration project, not a button. Decide which you need rather than assuming automatic rotation covers everything.
Rotating Application Secrets Without Downtime
A database password used by many instances cannot change atomically; if you change it in one place, every other holder breaks. The technique is the overlapping double secret: the datastore accepts both the old and the new credential for a window, the deploy rolls the new value out to all holders, then the old value is removed. Two-version support, either at the datastore or at a proxy, is what makes the overlap possible.
# 1) Create a second credential alongside the current one (both valid)
vault write -f database/rotate-root # rotate the admin, not the app
vault write database/creds/orders-app role=orders-app # new dynamic credential
# 2) Roll the new value to all holders via the secret manager
# (applications read dynamically, so they pick it up on next lease renewal)
# 3) After the overlap window, revoke the old credential
vault lease revoke <old-lease-id>
# Verify no holder is still using the old credential before revoking:
vault list sys/leases/lookup/database/creds/orders-app
Dynamic Secrets and Lease TTLs
Static secrets require manual rotation. Dynamic secrets are generated on demand with a short lease: the client asks the secret manager for a database credential, gets one that is unique to it, and the credential is revoked automatically when the lease expires. Nothing can be leaked by a shared secret because there is no shared secret; each holder has its own. This is a stronger model when the datastore supports creating users on the fly.
Short leases reduce exposure but require the client to renew and to handle renewal failures by re-authenticating. Set the lease TTL to a value longer than the longest expected operation but short enough that a leaked credential expires quickly, and monitor for clients that stop renewing, which usually indicates a broken secret path.
Operational Discipline
Automate rotation and test it before you need it. A rotation procedure that has never run in production fails the first time it is invoked, typically during an incident when someone is trying to reduce exposure. Schedule rotations and rotate on demand after any suspected compromise, and keep the runbook to a sequence of commands, not a paragraph of judgement.
Never store the plaintext secret in logs, error messages or telemetry. Redact credentials at the logging boundary so a rotation does not leak the new value into a log aggregator. Set alerts on rotation failures, because a rotation that silently fails leaves you believing a secret is fresh when it is not, which is worse than a known-stale one.
Conclusion
A KMS makes rotation practical: envelope encryption separates the data key from the master key, key versions let old ciphertext keep decrypting after a master key rotates, and dynamic secrets issue per-client credentials with short leases. For shared credentials, rotate with an overlap so both values are valid while the new one propagates, then revoke the old. Automate and rehearse the procedure, redact secrets from telemetry and alert on rotation failure. Rotation then becomes a scheduled, boring event instead of a crisis.
Sources: AWS KMS: envelope encryption, AWS KMS: key rotation, HashiCorp Vault: dynamic secrets.
FAQ
- Do I need to re-encrypt all my data when a KMS key rotates?
- Usually no. Versioned keys keep the old key version available for decryption, so existing ciphertext still decrypts while new encryptions use the new version. Re-encryption is only needed if your threat model requires old ciphertext to become undecryptable.
- How do I rotate a shared password without an outage?
- Use an overlap: make the datastore accept both the old and the new credential, roll the new value out to all holders, and only then revoke the old one. Two-version support at the datastore or a proxy is what makes the overlap possible.
Report a problem with this articleOpens a pre-filled issue on GitHub.