Skip to content
Trapdoor·Lab

Envelope encryption (KMS)

1Toy

A data key in an envelope

Envelope encryption uses two keys. The data is encrypted with a random data key (DEK, data encryption key), a separate one for each object, and that key is itself encrypted — “wrapped” — by a master key (KEK, key encryption key) that lives in a KMS and never leaves it. Next to the data you store only the ciphertext and the wrapped data key, and only keys ever travel to the KMS — never the data itself. The KMS wouldn’t take large data anyway: with a symmetric key, AWS KMS encrypts at most 4,096 bytes directly — enough for a key, not for a file.

Here the site’s server plays the KMS. The master key exists only in its memory: eight versions are created at startup and lost on restart, whereas a real KEK sits in an HSM inside the KMS. The generate-data-key call returns a fresh random 32-byte data key twice: in plaintext and wrapped by the master key with AES-256-GCM, with the encryption context bound as AAD. Your browser encrypts your text or file (up to 5 MB) locally with that key — AES-GCM, again with the context as AAD — throws the plaintext data key away and keeps the ciphertext, the wrapped key and the context. A counter shows how many bytes went to the KMS, and how many of your data did: 0 B.

Envelope encryption with this site’s KMS

Your browser encrypts the data with a random data key (DEK). This site’s KMS keeps the master key (KEK) only in the server’s memory: it hands out data keys and decrypts them, but never sees the data.

82 B
19 / 256 B

A public label for the record. The KMS binds the encrypted data key to it, and AES-GCM binds the ciphertext to it (as AAD).

The context can be at most 256 B of UTF-8.

Enter the data and a context. The master key never leaves the server — you have to ask the KMS for a data key.

What went to the KMS

Sent to the KMS: 0 B · requests: 0 (context, credential, encrypted key)

Your data sent to the KMS: 0 B of 82 B

Reading takes two steps: the KMS unwraps the data key — and refuses if you give it a different context — then your browser decrypts the data locally. Rotation re-wraps the data key under the next master key version inside the KMS, like the ReEncrypt operation in AWS KMS: the plaintext data key never comes out, and the data ciphertext stays byte-for-byte identical. The demo server has no accounts, so the app’s permission to use the KMS key, which IAM grants in a real cloud, is played by a random token the page keeps in memory: the KMS unwraps data keys only for whoever presents it.

2Break it

A thief with a copy of the database

In “Break it” mode an attacker steals two databases generated by the site: fake records, each with its own data key. From the correct one they get ciphertexts, wrapped keys and contexts. They cannot guess a data key — that is 2²⁵⁶ possibilities — and only the KMS can unwrap one, which it refuses to do without the app’s permission, so not a single record can be read. In the buggy one the developer also stored every data key in plaintext next to the data, so everything decrypts locally and the KMS never even learns that a theft happened.

This protection ends where the thief also gets hold of the app’s credentials, for example from its environment variables: then they can call the KMS just as the app does. That is why access to a KMS key is narrowed by key policies (only the app’s role, only with a matching context), every use of the key lands in an audit log — CloudTrail on AWS — and revoking the permission cuts off further reads.

3In the real world

Where envelope encryption runs

  • AWS KMS — GenerateDataKeyA single call returns a random data key in two copies: in plaintext in the Plaintext field and encrypted under the KMS key in CiphertextBlob. The documentation recommends encrypting the data with the plaintext copy, erasing it from memory straight away and storing CiphertextBlob with the data.Source (AWS KMS — GenerateDataKey)
  • AWS KMS — encryption contextThe context is a set of non-secret key–value pairs that KMS uses as AAD: decryption requires exactly the same context. It is not secret — it appears in CloudTrail logs — and key policies can make access conditional on it.Source (AWS KMS — encryption context)
  • AWS KMS — key rotationAutomatic rotation, every 365 days by default, changes only the current key material and keeps the older material, so old ciphertexts still decrypt. Rotation by itself does not re-wrap data keys or re-encrypt any data.Source (AWS KMS — key rotation)
  • Google Cloud KMSGoogle recommends generating data keys locally and a new one on every write, never using one data key for two users’ data, storing it encrypted close to the data, and keeping KEKs centrally and rotating them regularly and after a suspected incident.Source (Google Cloud KMS)
  • Azure Key Vault — wrapKeyThe wrapKey operation encrypts a symmetric key with a key encryption key previously stored in Key Vault, for example with RSA-OAEP-256 or A256KW, and requires the keys/wrapKey permission.Source (Azure Key Vault — wrapKey)
  • Kubernetes — KMS v2With the KMS v2 provider, stable since Kubernetes 1.29, the API server encrypts data at rest, such as Secrets, with a single-use data key derived by a KDF from a secret seed, and the data keys are encrypted by a KEK managed in an external KMS.Source (Kubernetes — KMS v2)
4Take it to your project

One key per object, the master key in a KMS

Good practice

Generate a new data key for every object — record, file, message — and store it next to the data only in wrapped form. Keep the master key in a KMS or HSM: the app asks for keys to be wrapped and unwrapped but never sees the master key. Bind a context, such as the table and record ID, as AAD — the KMS checks it when unwrapping the key and AES-GCM when decrypting the data — so a wrapped key cannot be attached to someone else’s record. Erase the plaintext data key from memory right after use. Rotate the master key: it is cheap, because you re-wrap 32-byte keys, not gigabytes of data.

JavaScript
import { KMSClient, GenerateDataKeyCommand } from '@aws-sdk/client-kms';

const kms = new KMSClient({});
const context = { table: 'orders', id: '42' };
// a new data key for every record
const { Plaintext, CiphertextBlob } = await kms.send(new GenerateDataKeyCommand({
  KeyId: 'alias/orders', KeySpec: 'AES_256', EncryptionContext: context }));
const dek = await crypto.subtle.importKey(
  'raw', Plaintext, 'AES-GCM', false, ['encrypt']);
Plaintext.fill(0); // plaintext data key out of memory at once
const iv = crypto.getRandomValues(new Uint8Array(12));
const aad = new TextEncoder().encode('orders/42');
const ciphertext = await crypto.subtle.encrypt(
  { name: 'AES-GCM', iv, additionalData: aad }, dek, data);
// store: ciphertext, iv, CiphertextBlob, context
C#
var kms = new AmazonKeyManagementServiceClient();
var context = new Dictionary<string, string> { ["table"] = "orders", ["id"] = "42" };
var resp = await kms.GenerateDataKeyAsync(new GenerateDataKeyRequest {
    KeyId = "alias/orders", KeySpec = DataKeySpec.AES_256, EncryptionContext = context });
byte[] dek = resp.Plaintext.ToArray();
byte[] nonce = RandomNumberGenerator.GetBytes(12);
byte[] ct = new byte[data.Length], tag = new byte[16];
using (var gcm = new AesGcm(dek, tagSizeInBytes: 16))
    gcm.Encrypt(nonce, data, ct, tag, Encoding.UTF8.GetBytes("orders/42"));
CryptographicOperations.ZeroMemory(dek); // wipe the copy; drop resp.Plaintext at once
// store: ct, nonce, tag, resp.CiphertextBlob.ToArray(), context
Anti-pattern

Don’t store the plaintext data key in the database, not even “temporarily” — whoever steals the database then gets everything without asking the KMS, and the KMS logs show no trace of it. Don’t encrypt everything with one data key: its leak exposes the whole database, and with random nonces in AES-GCM one key is good for at most 2³² encryptions. Don’t keep the master key in code, a config file or an environment variable: then anyone who can read the config can read the data too, and you lose rotation, auditing and the ability to revoke access.

JavaScript
// ✕ the plaintext data key in the same row as the data:
// a database thief never has to ask the KMS
await db.orders.insert({ id: 42, ciphertext, iv, dataKey: Plaintext });
C#
// ✕ the master key in an environment variable and one key for every record
static readonly byte[] Key =
    Convert.FromBase64String(Environment.GetEnvironmentVariable("MASTER_KEY")!);