How-To Guide

How to Implement Envelope Encryption with a KMS

Protect data at rest with envelope encryption: a KMS master key wraps per-object data keys, limiting blast radius and enabling rotation.

On this page

  1. Introduction
  2. Why Not Encrypt Everything with One Key
  3. Generating a Data Key
  4. Storing the Wrapped Key
  5. Key Rotation
  6. Access Control and Auditing
  7. Caching Plaintext Data Keys
  8. Common Pitfalls and Conclusion

Introduction

Encrypting data with a single key means that key is enormously valuable and must be stored somewhere safe, which is a contradiction: to use it, the application must be able to read it. Envelope encryption resolves this by splitting the problem. A key management service (KMS) holds a master key that never leaves the service; the application asks the KMS to generate or wrap a per-object data key, encrypts the data with that data key, and stores only the wrapped key alongside the ciphertext. The master key protects many data keys, and the data keys never need to be stored in the clear.

Why Not Encrypt Everything with One Key

One key for all data is simple but wrong for several reasons. The blast radius of a leak is the whole dataset. Rotating the key means re-encrypting everything. A key that must be read to encrypt and decrypt is exposed on every host that touches the data. And a large system may need different keys per tenant or per data class, which one key cannot express.

Envelope encryption separates the long-lived master key from the short-lived data keys. The master key stays inside the KMS, used only through API calls that wrap and unwrap data keys. The data keys are generated per object, used briefly, and stored only in wrapped form. A compromised host can unwrap keys only through the KMS, which logs and can deny.

# envelope encryption
plaintext --(data key)--> ciphertext           stored with wrapped data key
data key  --(wrapped by KMS master key)--> wrapped key
# stored record = ciphertext || wrapped_data_key || iv || key_id
# master key never leaves the KMS; only wrap/unwrap calls cross the boundary

Generating a Data Key

The KMS can generate a data key and return both the plaintext key and its wrapped form in one call. The application uses the plaintext key to encrypt the object, then discards it from memory, storing only the ciphertext and the wrapped key. The plaintext key should exist only in memory, briefly, and never be written to disk or a log.

Use an authenticated encryption mode such as AES-GCM or ChaCha20-Poly1305 so the ciphertext is tamper-evident. Provide additional authenticated data (AAD) that binds the ciphertext to its context, such as the object id or the tenant, so a ciphertext moved to a different record fails to decrypt.

import { generateDataKey, decrypt as kmsDecrypt } from './kms';

export async function encryptObject(id: string, plaintext: Buffer) {
  const { plaintextKey, wrappedKey } = await generateDataKey({ keyId: MASTER_KEY_ID });
  const iv = crypto.getRandomValues(new Uint8Array(12));
  const cipher = crypto.createCipheriv('aes-256-gcm', plaintextKey, iv);
  cipher.setAAD(Buffer.from(id));            // bind ciphertext to its id
  const ct = Buffer.concat([cipher.update(plaintext), cipher.final()]);
  return { id, ct, iv, tag: cipher.getAuthTag(), wrappedKey }; // store all of it
}

export async function decryptObject(rec: EncryptedRecord) {
  const key = await kmsDecrypt({ keyId: MASTER_KEY_ID, ciphertext: rec.wrappedKey });
  const decipher = crypto.createDecipheriv('aes-256-gcm', key, rec.iv);
  decipher.setAAD(Buffer.from(rec.id));
  decipher.setAuthTag(rec.tag);
  return Buffer.concat([decipher.update(rec.ct), decipher.final()]);
}

Storing the Wrapped Key

The wrapped data key is safe to store alongside the ciphertext because it cannot be unwrapped without access to the KMS and the master key. Store the wrapped key, the initialisation vector, the authentication tag and the id of the KMS key used, so old records can still be decrypted after a rotation. Without the key id, a rotation makes old data unreadable.

Treat the metadata as part of the record and keep it with the ciphertext, so decryption is self-contained: given the record and KMS access, you can decrypt without out-of-band knowledge. A common mistake is to store the IV or the key id separately and lose the association, which makes the data unrecoverable even with the key.

CREATE TABLE secrets (
  id          uuid PRIMARY KEY,
  ciphertext  bytea NOT NULL,
  iv          bytea NOT NULL,
  tag         bytea NOT NULL,
  wrapped_key bytea NOT NULL,
  kms_key_id  text  NOT NULL,   -- which master key wrapped it (for rotation)
  created_at  timestamptz NOT NULL DEFAULT now()
);
-- decrypt = unwrap(wrapped_key via kms_key_id) then AEAD-decrypt(ciphertext, iv, tag, aad=id)

Key Rotation

Rotation replaces the master key without re-encrypting all the data. Because each record stores the wrapped data key and the id of the master key that wrapped it, you keep the old master key available for unwrapping and start wrapping new data with the new one. Existing records stay readable; they are only re-wrapped lazily or in a background job.

Two rotation strategies: re-encrypt lazily, where a record is re-wrapped the next time it is written, or a background job that re-wraps all records. Lazy is cheaper and spreads the cost but leaves old wrapped keys around for a long time; a background job converges faster but needs careful throughput control. Either way, never delete the old master key until no record references it.

# master key rotation with envelope encryption
1. enable new master key K2 in the KMS (keep K1 enabled)
2. write new/updated records using K2
3. background job re-wraps records still pointing at K1 (rewrap only;
   the data key is unchanged, so ciphertext is not recomputed)
4. when no record references K1, disable then delete K1
# crucial: the kms_key_id column is what makes step 4 safe

Access Control and Auditing

The KMS is the choke point, so its access control is the real security boundary. Grant decrypt only to the services that must read the data, and use separate master keys per data class or tenant so a compromise of one service’s identity cannot unwrap another’s data. This is the blast-radius limiting that a single key cannot provide.

Enable KMS audit logging and alert on anomalous patterns: an unexpected principal decrypting, a spike in unwrap calls, or decrypts from an unusual location. Because every unwrap is an API call, the KMS gives you an audit trail of exactly who accessed which key and when, which is far stronger than trusting application logs.

# kms access control
principals                      permitted actions        key scope
payments-service                generateDataKey, decrypt  key/payments
analytics-service               decrypt                   key/analytics (read-only)
everyone else                   (none)                    -
# alert on: unexpected principal, unwrap spike, off-hours decrypt, new region

Caching Plaintext Data Keys

Unwrapping on every read adds latency and KMS cost. Caching the plaintext data key briefly, in memory, keyed by the wrapped key, reduces calls. But the cache is itself sensitive: it holds keys in the clear, so it must be short-lived, bounded, and cleared on process shutdown. A long-lived plaintext key cache weakens the very isolation envelope encryption provides.

Prefer caching the data key rather than a derived master key, and never cache across tenants or data classes, so a cache entry only helps one class of records. Measure the cache hit rate against the KMS call latency to decide the TTL, and keep it small enough that a memory disclosure does not hand over many keys.

// Short-lived in-memory cache of unwrapped data keys.
const ttlMs = 30_000;
const cache = new Map<string, { key: Buffer; exp: number }>();

async function unwrapCached(wrappedKey: Buffer): Promise<Buffer> {
  const k = wrappedKey.toString('base64');
  const hit = cache.get(k);
  if (hit && hit.exp > Date.now()) return hit.key;
  const key = await kmsDecrypt({ keyId: MASTER_KEY_ID, ciphertext: wrappedKey });
  cache.set(k, { key, exp: Date.now() + ttlMs });
  return key;
}

Common Pitfalls and Conclusion

Do not lose the key id with the record, or rotation orphans the data. Do not use a non-authenticated cipher mode, which lets an attacker tamper undetected. Do not write the plaintext data key to disk or logs. Do not cache plaintext keys for long. Do not grant decrypt broadly. And do not delete an old master key until you have proven no record references it.

Envelope encryption splits the key problem: a KMS-held master key wraps per-object data keys, so the valuable key never leaves the KMS and leaks are contained to one object. Generate a data key per object, use authenticated encryption with the object id as AAD, store the wrapped key with its key id, rotate the master key without re-encrypting, and make the KMS access control the real boundary with audit on every unwrap.

Sources: AWS KMS: Envelope encryption, Google Cloud KMS: envelope encryption, NIST SP 800-57: Key management.

FAQ

Why store the wrapped data key with the ciphertext?
Because it cannot be unwrapped without KMS access and the master key, so it is safe to store, and it makes each record self-contained for decryption. Also store the master key id so the record can still be decrypted after a rotation.
How does rotation work if data is already encrypted?
You keep the old master key for unwrapping and start wrapping new records with the new one. Because the data key is unchanged, rotation only re-wraps the key, not the ciphertext, so a background job or lazy re-wrap converges without recomputing the data encryption.

Related Examples