SECURITY ENGINEERING · PART 4 · CRYPTOGRAPHY IN PRACTICE · KEYS · 55 OF 229

Key Rotation and Key Versioning Without Downtime

Keys and secrets must be replaced regularly and immediately after a leak, without breaking the system. This episode shows how: key versions stored with every ciphertext, decrypt with any version but encrypt with the newest, a working rotation with real output, rewrapping 100,000 data keys in 0.23 seconds instead of re-encrypting the data, dual credentials for passwords and API keys, and a rotation policy by key type.

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 9
  9. 10
  10. 11
  11. 12
  12. 13
  13. 14
  14. 15
  15. 16
  16. 17
  17. 18
  18. 19
  19. 20
  20. 21
  21. 22
  22. 23
  23. 24
  24. 25
  25. 26
  26. 27
  27. 28
  28. 29
  29. 30
  30. 31
  31. 32
  32. 33
  33. 34
  34. 35
  35. 36
  36. 37
  37. 38
  38. 39
  39. 40
  40. 41
  41. 42
  42. 43
  43. 44
  44. 45
  45. 46
  46. 47
  47. 48
  48. 49
  49. 50
  50. 51
  51. 52
  52. 53
  53. 54
  54. 55
  55. 56
  56. 57
  57. 58
  58. 59
  59. 60
  60. 61
  61. 62
  62. 63
  63. 64
  64. 106
  65. 107
  66. 108
  67. 109
  68. 110
  69. 111
  70. 112
  71. 113
  72. 114
  73. 115
  74. 116
  75. 117
  76. 118
  77. 119
  78. 120
  79. 121
  80. 122
  81. 123
  82. 124
  83. 125
  84. 126
  85. 127
  86. 128
  87. 129
  88. 130
  89. 131
  90. 132
  91. 133
  92. 134
  93. 135
  94. 136
  95. 137
  96. 138
  97. 139
  98. 140
  99. 141
  100. 142
  101. 143
  102. 144
1 / 14

Press play to hear the narration, or step through at your own pace.

Key takeaways

  • Version every key
  • tag every ciphertext
  • encrypt with newest, decrypt with any
  • rewrap data keys

Notes

Why rotate

Why rotate? It limits how much data one stolen key exposes. It removes access from people who have left and from systems that no longer need it. Some algorithms have real limits, such as the number of messages per key in GCM. Standards like PCI DSS and SOC two expect it. And the most practical reason: a team that never rotates has no working procedure, so on the day a key leaks, the emergency rotation causes an outage.

Reasons
  • limits the data exposed by one compromised key
  • removes access from people who have left
  • cryptographic limits: GCM nonces per key
  • compliance: PCI DSS, SOC 2, ISO 27001 expect it
  • practice: if you never rotate, you cannot do it in an emergency

The naive way fails

The naive way is to swap the key in the configuration. Immediately, every existing record fails to decrypt. So teams try to re-encrypt everything first, which takes hours or days for a large dataset, and during that time some records use the old key and some the new, with nothing recording which is which. After one painful attempt, rotation is postponed indefinitely. The fix is to plan for several keys existing at once.

What goes wrong
  • replace the key in config: all old data fails to decrypt
  • re-encrypt everything first: hours or days, and both versions exist meanwhile
  • no record of which key encrypted what
  • so rotation gets postponed, for years

Key versioning

The design is key versioning. Every key has a version number, and every ciphertext stores the version it was encrypted with, in a small header. To encrypt, always use the newest version. To decrypt, read the tag and fetch that version. Old versions stay available, for decryption only. Rotation then means adding a new version and making it current. Nothing breaks, because old data still names its own key.

The design
  • every key has a version id
  • every ciphertext stores the version it was made with encrypt: always the newest version
  • decrypt: read the tag, use that version
  • old versions stay available for decryption only rotation = add a version

Run it

Here it is with a real library. We encrypted a value with key one. Then we built a key ring with key two first and key one second. The old token still decrypts, because the ring tries both. Calling rotate re-encrypts it under key two. After that, key two alone reads the new token, and key one cannot. We rotated one hundred thousand tokens in under two seconds. Once every token is rotated, key one can be retired.

rotation with MultiFernet
tok = Fernet(k1).encrypt(b"card=4111...")
mf = MultiFernet([Fernet(k2), Fernet(k1)])
mf.decrypt(tok)        # works: tries both
new = mf.rotate(tok)   # now under k2
Fernet(k2).decrypt(new)   # works
Fernet(k2).decrypt(tok)   # InvalidToken
Fernet(k1).decrypt(new)   # InvalidToken

# 100,000 tokens rotated in 1.84 s

Rewrap, not re-encrypt

With envelope encryption, rotation gets much cheaper. To rotate the master key, you unwrap each data key with the old master and wrap it with the new one. We rewrapped one hundred thousand data keys in zero point two three seconds. The data itself is not touched. Compare re-encrypting the data: a terabyte means reading and writing every byte. So master keys rotate often and cheaply, and data keys are replaced when data is rewritten.

rewrap vs re-encrypt, measured
# rewrap 100,000 data keys under
# a new master key:        0.23 s

# re-encrypt 100 MB of data
# under a new data key:     0.15 s
# 1 TB at that rate: ~25 minutes
# of CPU, plus reading and
# writing every byte

# rewrap touches 40 bytes per object

KMS automatic rotation

Cloud key services do this for you. Turn on automatic rotation, and the service creates new key material on a schedule. The key identifier stays the same, old material is kept so old data still decrypts, and your code changes nothing. But understand the limit: it does not re-encrypt existing data. That is fine for routine rotation. After an actual compromise, it is not enough. You need a new key and you must re-encrypt what the old one protected.

Managed rotation
  • turn it on: new key material on a schedule (yearly by default, shorter possible)
  • the key id stays the same; old material is kept to decrypt old data
  • your code changes nothing
  • it does NOT re-encrypt existing data
  • after a leak: new key and re-encrypt, not just rotate

Passwords and API keys

Passwords, API keys and tokens rotate with the same idea: two valid at once. Create the new credential while the old still works. Deploy the new one to every client. Watch the logs to see whether the old one is still being used. Disable the old one, wait, then delete it. This needs systems that allow two active credentials per service, which is why database users and cloud access keys support exactly that. A secrets manager automates the whole sequence.

Dual credentials
  • 1. create the new credential; both old and new work
  • 2. deploy the new one to all clients
  • 3. watch: is the old one still being used?
  • 4. disable the old; wait
  • 5. delete it
  • needs: two active keys per user or service
  • a secrets manager automates it

A rotation policy

A typical policy by type. Master keys in a key service: yearly and automatic. Data keys: per object, replaced when data is rewritten. TLS certificates: ninety days or less. Database and service passwords: thirty to ninety days through a secrets manager. Cloud access keys: ninety days, or better, replace them with short-lived roles so there is nothing to rotate. Signing keys: one to two years. And on any suspicion of compromise: immediately.

By type
  • KMS master keys: yearly, automatic
  • data keys: per object, or when data is rewritten
  • TLS certificates: 90 days or less, automatic
  • database and service passwords: 30 to 90 days
  • cloud access keys: 90 days; better, none at all on any suspicion: now

When a key leaks

When a key leaks, treat it as an incident and follow a fixed order. Create the new key first. Switch every writer to it. Then revoke or disable the old one. Re-encrypt the data the old key protected. Search the logs for everything the old key accessed while it was exposed. And find how it leaked, so it does not happen again. One point matters most: deleting a secret from a git repository does not un-leak it. Only rotation does.

Compromise runbook
  • 1. create the new key first
  • 2. switch all writers to it
  • 3. revoke or disable the old one
  • 4. re-encrypt data the old key protected
  • 5. search logs: what did the old key access?
  • 6. find how it leaked; fix it
  • removing it from git history is not rotation

Rotate less by design

The best rotation is the one you never have to do. Use short-lived credentials: cloud roles instead of access keys, OIDC tokens for pipelines, workload identity for services. Use dynamic secrets, where a tool like Vault creates a database user for each application, valid for an hour. Issue short-lived certificates from an internal authority. When nothing lives longer than a few hours, a leaked secret is already dead, and rotation happens by itself.

Better than rotation
  • short-lived credentials: cloud roles, OIDC tokens for CI, workload identity
  • dynamic secrets: Vault makes a database user per app, valid for an hour
  • short-lived certificates from an internal CA
  • nothing long-lived means nothing to rotate or leak

Common mistakes

Mistakes. No key version stored with the data, so nobody knows which key reads what. Deleting the old key before every record is re-encrypted, which destroys data permanently. Rotating by hand, once, for an audit. A rotation that requires a deployment and downtime. A secret rotated in one place and still used in five others. A runbook that has never been tested. And no inventory of what secrets exist and who owns them.

Avoid these
  • no key version stored with the data
  • deleting the old key before everything is re-encrypted
  • rotating by hand, once
  • a rotation that needs a deploy and downtime
  • rotated in one place, still used in five others
  • never testing the runbook
  • no inventory of secrets

Say it like this

In the interview: I version the keys and store the version with every ciphertext. New writes use the newest version, and reads use whichever version the record names, so nothing breaks at the moment of rotation. With envelope encryption I rewrap the data keys under the new master in the background, then retire the old version once nothing references it. For credentials I run old and new in parallel. After a compromise I also re-encrypt and review access logs.

In the interview
  • "Version the keys and tag
  • every ciphertext with its version. Encrypt with the newest, decrypt with any.
  • With envelope encryption, rewrap data keys under the new master in the background, then retire the old version.
  • After a leak, re-encrypt."

Interview questions

Q1What is key rotation?

Replacing a cryptographic key or secret with a new one, on a schedule or after suspected compromise, so that the amount of data and the length of time protected by any single key are limited. Old key versions are kept only as long as needed to decrypt existing data.

Q2How do you rotate an encryption key without downtime?

Use key versioning: store a key version identifier with every ciphertext, encrypt new data with the latest version and decrypt using the version named in the record. Old data remains readable, and it can be re-encrypted gradually in the background.

Q3What is key versioning?

Keeping multiple generations of a key under one logical name, each with a version identifier that is recorded alongside the data it encrypted. It allows new and old ciphertexts to coexist and makes rotation an additive, reversible operation.

Q4Does KMS automatic rotation re-encrypt existing data?

No. It generates new key material for future encrypt operations and retains previous material to decrypt older ciphertexts under the same key ID. To remove dependence on old material, the data or its data keys must be explicitly re-encrypted.

Q5What is the difference between rotating a key and re-encrypting data?

Rotation changes which key is used for new encryption. Re-encryption decrypts existing data and encrypts it again under a new key. With envelope encryption, rotating the master key only requires rewrapping data keys, which is far cheaper.

Q6How do you rotate an API key or database password safely?

Create a second credential while the first remains valid, deploy it to all consumers, confirm from logs that the old one is unused, then disable and later delete the old one. A secrets manager can automate this dual-credential process.

Q7How often should keys be rotated?

It depends on type and risk: commonly yearly for KMS master keys, 90 days or less for certificates and access keys, 30 to 90 days for service passwords, and immediately on any suspicion of compromise. Automation allows much shorter periods.

Q8What should you do when a secret is committed to a repository?

Treat it as compromised: issue a new secret, switch consumers, revoke the old one, and review logs for its use during the exposure. Removing it from the repository history alone is insufficient, because it may already have been copied.