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

Envelope Encryption, KMS and HSM Explained

Where do encryption keys live? This episode explains envelope encryption: data is encrypted with a data key, and the data key is wrapped by a master key that never leaves a KMS or HSM. With a working local example (a 32-byte data key wraps to 40 bytes, and the wrong master key fails), key hierarchies, what an HSM guarantees, KMS access policies, audit logs, and how attackers abuse KMS permissions.

  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

  • Data keys encrypt data
  • a master key wraps data keys
  • the master never leaves the HSM
  • every decrypt is checked and logged

Notes

The problem

Here is how encryption usually fails in practice. The key is in the source code, or a config file, or an environment variable on the same host. Or it sits in the same database as the encrypted column, or in the same backup. Then one breach gives the attacker both the data and the key, and the encryption did nothing. It may still pass a checklist that asks, is the data encrypted. Your job is to ask the better question: where is the key?

Where keys end up
  • in source code or a config file in the repo
  • in an environment variable on the same host
  • in the same database as the encrypted column
  • in the same bucket or backup
  • result: one breach gives the attacker data and key
  • auditors call this "encrypted"

Two kinds of key

The solution uses two kinds of key. A data encryption key, or DEK, encrypts the actual data. There are many of them: one per file, per record or per tenant. A key encryption key, or KEK, also called the master key, does only one thing: it encrypts data keys. Encrypting a key with another key is called wrapping. There are few master keys, and they are guarded far more tightly than any data.

The key hierarchy
  • DEK: data encryption key encrypts the actual data many of them, short-lived
  • KEK: key encryption key (master key, KMS key) only ever encrypts DEKs few, tightly guarded
  • encrypting a key with another key is called "wrapping"

Envelope encryption

Here is the full flow. The application asks the key management service for a data key, and receives it twice: once in plain form, and once wrapped by the master key. It encrypts the data locally with the plain key, using AES in GCM mode. It stores the ciphertext together with the wrapped key. Then it erases the plain key from memory. The data and its key now travel together, but the key is locked, and the master key never left the service.

Encrypt
  • 1. ask KMS for a data key: you get it in plain form AND wrapped by the master
  • 2. encrypt the data locally with the plain key
  • 3. store the ciphertext and the WRAPPED key together
  • 4. erase the plain key from memory
  • the master key never left

Decrypt

To decrypt, the application reads the ciphertext and the wrapped key, and sends only the wrapped key to the key management service. The service checks who is asking, checks the policy, writes an audit log entry, and returns the plain data key. The application decrypts locally. Notice two things. The data itself never goes to the service, so size and speed are not a problem. And every single decryption passes through an access check and a log.

Decrypt
  • 1. read the ciphertext and the wrapped key
  • 2. send only the wrapped key to KMS: "unwrap this"
  • 3. KMS checks identity and policy, logs the call, returns the plain key
  • 4. decrypt locally, erase the key
  • the data never goes to KMS

Run it locally

Here is the pattern run locally, with an ordinary key standing in for the master. A thirty two byte data key wraps to forty bytes. Unwrapping with a different master key raises an error, so a wrapped key is useless without the right master. And here is what we store beside the ciphertext: a key version, the wrapped key and the nonce, about a hundred bytes. That key version field matters, and the next episode on rotation depends on it.

wrap and unwrap
kek = AESGCM.generate_key(256)
dek = AESGCM.generate_key(256)
wrapped = aes_key_wrap(kek, dek)
len(dek), len(wrapped)   # (32, 40)

aes_key_unwrap(other_kek, wrapped)
# raises InvalidUnwrap

# stored beside the ciphertext:
# {"kv": 1, "wk": "3s31k5f6...",
#  "n": "Zm6mNhwS..."}

Why it works

Why is this better? An attacker who steals the disk, the bucket or the backup has ciphertext and wrapped keys, both useless without the key service. Access to decryption is controlled by one policy in one place, and can be revoked in seconds. Every decryption is logged. If one data key leaks, it exposes one object and not the whole dataset. And rotation becomes cheap, because you rewrap small keys instead of re-encrypting all the data.

What you gain
  • stolen storage: ciphertext and wrapped keys, both useless without KMS
  • access is one policy, in one place, and can be revoked
  • every decrypt is logged
  • a leaked data key exposes one object, not everything
  • rotation is cheap: rewrap the small keys

HSM

Under the key service sits a hardware security module. An HSM is a tamper-resistant device that generates keys and holds them so that they cannot be exported. You send it data, it performs the operation inside, and results come out. Even its administrators cannot read the keys. They are certified to a standard called FIPS one forty, usually level three. A cloud key management service is a fleet of HSMs with an API in front.

Hardware security module
  • a tamper-resistant device that generates and holds keys
  • keys are non-exportable: you send data in, results come out certified: FIPS 140-2 / 140-3 level 3 is typical
  • cloud KMS: an HSM fleet with an API in front
  • CloudHSM: a dedicated one

KMS in the cloud

Every provider has the same design: AWS KMS, Azure Key Vault, Google Cloud KMS, and Vault's transit engine for self-hosting. You choose between provider-managed keys, which are easy but give little control, and customer-managed keys, where you own the policy, the rotation and the logs. The key policy decides who may encrypt and who may decrypt. A core rule: the people who administer a key should not be the ones who can use it to decrypt.

Managed key services
  • AWS KMS, Azure Key Vault, Google Cloud KMS, Vault Transit
  • provider-managed keys: easy, little control
  • customer-managed keys: your policy, rotation and logs
  • key policy + IAM decide who may encrypt and decrypt
  • separate key admins from key users

How attackers abuse KMS

Attackers do not steal a master key from an HSM. They borrow the right to use it. A compromised role with decrypt permission on every key is as good as having the keys. Policies that trust a whole account are common. Attackers add grants for persistence. In cloud ransom attacks, they re-encrypt your data under a key they control, or schedule your key for deletion. And plain data keys sometimes leak into logs or memory dumps.

Attacks
  • a compromised role that has kms:Decrypt on *
  • key policies open to the whole account or to "*"
  • grants created quietly for persistence
  • ransom: re-encrypt your data under THEIR key, or schedule your key deletion
  • plain data keys in logs or crash dumps

Defend and detect

Defenses. Grant decrypt only to the roles that need it, on specific keys, never on everything. Use an encryption context, which is associated data for the key service: a decrypt call must present the same tenant or resource identifier used at encryption. Alert on key disabling, scheduled deletion, policy changes and unusual spikes in decrypt calls. Keep the deletion waiting period. And use separate keys for production and for each data classification.

Controls
  • least privilege: decrypt only for the roles that need it, on specific keys
  • encryption context: bind a key use to a tenant or resource
  • alert on: DisableKey, ScheduleKeyDeletion, policy changes, decrypt spikes
  • keep a deletion waiting period
  • separate keys per environment

Common mistakes

Mistakes. The key stored beside the data. Sending bulk data to the key service for encryption instead of using data keys, which is slow, costly and size-limited. Wildcard key permissions. One master key shared by every environment and every tenant. Caching plain data keys forever, or writing them to logs. No alerts on key policy changes. And no tested plan for what happens if a key is deleted or a region is lost.

Avoid these
  • the key beside the data
  • sending bulk data to KMS instead of using data keys
  • kms:* or Decrypt on *
  • one master key for all environments and tenants
  • caching plain data keys forever, or logging them
  • no alerts on key changes
  • no tested key recovery

Say it like this

In the interview: data is encrypted locally with a data key, using AES in GCM mode. The data key is wrapped by a master key that never leaves the key management service or its HSM, and the wrapped key is stored with the data. To read, the application asks the service to unwrap the key, which enforces the access policy and logs the call. Stolen storage is useless by itself, access is centrally controlled, and rotation only rewraps keys.

In the interview
  • "Data is encrypted locally
  • with a data key. That key is wrapped by a master key that never leaves the KMS or HSM, and the wrapped key is stored
  • with the data. To read, the app asks KMS to unwrap, which enforces policy and logs it.
  • Rotation only rewraps keys."

Interview questions

Q1What is envelope encryption?

A pattern in which data is encrypted with a data encryption key (DEK), and the DEK is itself encrypted (wrapped) with a key encryption key (KEK) held in a KMS or HSM. The wrapped DEK is stored alongside the ciphertext, and the KEK never leaves the key service.

Q2What is the difference between a DEK and a KEK?

A data encryption key encrypts the data itself; there are many, and they are stored only in wrapped form. A key encryption key, or master key, only encrypts DEKs; there are few, and they are kept inside a KMS or HSM under strict access control.

Q3Why not send all data to the KMS for encryption?

KMS encryption operations are limited to small payloads (4 KB in AWS KMS), add network latency and cost per call, and would expose all data to the service. Envelope encryption keeps bulk encryption local and fast while the KMS protects only the small data keys.

Q4What is an HSM?

A hardware security module: a tamper-resistant device that generates, stores and uses cryptographic keys so that the key material cannot be extracted. HSMs are validated against standards such as FIPS 140-3 and underpin cloud KMS services and certificate authorities.

Q5What is the difference between a KMS and an HSM?

An HSM is the hardware that protects keys. A KMS is a managed service on top of HSMs that adds an API, key policies, identity integration, rotation and audit logging. A dedicated HSM service gives single-tenant control at higher cost and effort.

Q6What is a customer-managed key (CMK)?

A KMS key that the customer creates and controls, including its key policy, rotation schedule, grants and deletion, as opposed to a provider-managed key. It provides control, auditability and the ability to revoke access to data by disabling the key.

Q7What is encryption context in KMS?

Additional authenticated data supplied on encrypt that must be supplied identically on decrypt. It binds a ciphertext to a tenant, resource or purpose, can be required in key policies, and appears in audit logs.

Q8How do attackers abuse KMS?

By compromising identities that hold decrypt permissions, exploiting over-broad key policies or grants, re-encrypting data under attacker-controlled keys, or scheduling key deletion for extortion. Least privilege and alerts on key management events are the main defenses.