Nov 20, 20266 min read

Envelope Encryption with AWS KMS in Node.js

Envelope encryption uses a KMS key to protect small data keys, and the data keys encrypt your records locally. How GenerateDataKey and Decrypt work, a Node.js example with AES-256-GCM, encryption context, key rotation and cost, plus a TypeScript service on Encore.

Illustration for Envelope Encryption with AWS KMS in Node.js

Some data should stay unreadable even to someone holding a database dump, such as tokens for third-party accounts or national IDs. Encrypting it in the application with a key stored in the same environment only moves the problem.

Envelope encryption keeps the master key inside AWS KMS, where it never leaves the service. This guide explains the flow, the parts of the KMS API you need and how to build it in Node.js and in a TypeScript service on Encore.

How does envelope encryption work?

KMS holds a key you never see in plaintext: to encrypt a record, ask KMS for a data key with GenerateDataKey, which returns the key twice: in plaintext, and encrypted under your KMS key. Encrypt the record locally with the plaintext key, discard it, and store the encrypted data key beside the ciphertext. To read the record, send the encrypted data key to KMS with Decrypt, get the plaintext key back and decrypt locally. AWS calls this envelope encryption.

The design means an attacker needs both the stored data and permission to call KMS, and KMS logs every call to CloudTrail.

Why not call KMS Encrypt directly?

Encrypt takes at most 4 KB of plaintext, and every call is a network round trip with a per-request charge and a rate limit. A data key lets you encrypt any size locally with AES-256-GCM. A common optimization caches a data key for a short time and reuses it for many records, trading a larger blast radius per key for fewer KMS calls, and a per-record key is simplest when volumes are low.

What is the encryption context?

Pass an EncryptionContext of non-secret key-value pairs on both GenerateDataKey and Decrypt, for example { tenant: "acme", table: "tokens" }. KMS verifies it on decrypt, so a data key stolen from one tenant's row cannot be used for another, and it is recorded in CloudTrail so audits show whose data was decrypted. Never put secrets in it.

A Node.js example

import { KMSClient, GenerateDataKeyCommand, DecryptCommand } from "@aws-sdk/client-kms"; import { createCipheriv, createDecipheriv, randomBytes } from "node:crypto"; const kms = new KMSClient({}); const KEY_ID = process.env.KMS_KEY_ID!; export async function encrypt(plaintext: Buffer, context: Record<string, string>) { const { Plaintext, CiphertextBlob } = await kms.send( new GenerateDataKeyCommand({ KeyId: KEY_ID, KeySpec: "AES_256", EncryptionContext: context }), ); const iv = randomBytes(12); const cipher = createCipheriv("aes-256-gcm", Plaintext!, iv); const data = Buffer.concat([cipher.update(plaintext), cipher.final()]); Plaintext!.fill(0); // drop the plaintext key from memory return { dataKey: Buffer.from(CiphertextBlob!), iv, tag: cipher.getAuthTag(), data }; } export async function decrypt( rec: { dataKey: Buffer; iv: Buffer; tag: Buffer; data: Buffer }, context: Record<string, string>, ) { const { Plaintext } = await kms.send( new DecryptCommand({ CiphertextBlob: rec.dataKey, EncryptionContext: context }), ); const decipher = createDecipheriv("aes-256-gcm", Plaintext!, rec.iv); decipher.setAuthTag(rec.tag); const out = Buffer.concat([decipher.update(rec.data), decipher.final()]); Plaintext!.fill(0); return out; }

AES-GCM needs a unique IV for every encryption under one key, so generate 12 random bytes each time and store them with the record, along with the authentication tag. Node's crypto module provides the cipher.

How do rotation and cost work?

Turn on automatic rotation for the KMS key, and old data keys keep decrypting because KMS retains previous key material, as described in the key rotation documentation. Records are not re-encrypted by rotation, since only the wrapping changes underneath. Costs are a monthly fee per key plus a charge per request, so caching data keys for hot paths cuts the request count, and one key per environment or data class is usually enough.

Envelope encryption with Encore

Encore

Encore brings infrastructure from code to the storage side of this pattern: the Postgres database that holds the encrypted records is declared in the service, runs locally under encore run and is provisioned on RDS in your AWS account. The KMS key itself is created and governed in your AWS account, and the service reads its ID from an Encore secret.

Set up the app

Get started
brew install encoredev/tap/encore &&
encore app create
Copy

Run in your terminal to get started locally.

-- vault/migrations/1_create_tokens.up.sql CREATE TABLE tokens ( tenant TEXT NOT NULL, name TEXT NOT NULL, data_key BYTEA NOT NULL, iv BYTEA NOT NULL, tag BYTEA NOT NULL, data BYTEA NOT NULL, PRIMARY KEY (tenant, name) );
// vault/vault.ts import { api, APIError } from "encore.dev/api"; import { secret } from "encore.dev/config"; import { SQLDatabase } from "encore.dev/storage/sqldb"; import { KMSClient, GenerateDataKeyCommand, DecryptCommand } from "@aws-sdk/client-kms"; import { createCipheriv, createDecipheriv, randomBytes } from "node:crypto"; const db = new SQLDatabase("vault", { migrations: "./migrations" }); const kmsKeyId = secret("KmsKeyId"); const kms = new KMSClient({}); export const put = api( { method: "PUT", path: "/vault/:tenant/:name", expose: false }, async ({ tenant, name, value }: { tenant: string; name: string; value: string }): Promise<void> => { const context = { tenant, table: "tokens" }; const { Plaintext, CiphertextBlob } = await kms.send( new GenerateDataKeyCommand({ KeyId: kmsKeyId(), KeySpec: "AES_256", EncryptionContext: context }), ); const iv = randomBytes(12); const cipher = createCipheriv("aes-256-gcm", Plaintext!, iv); const data = Buffer.concat([cipher.update(value, "utf8"), cipher.final()]); const tag = cipher.getAuthTag(); Plaintext!.fill(0); await db.exec` INSERT INTO tokens (tenant, name, data_key, iv, tag, data) VALUES (${tenant}, ${name}, ${Buffer.from(CiphertextBlob!)}, ${iv}, ${tag}, ${data}) ON CONFLICT (tenant, name) DO UPDATE SET data_key = EXCLUDED.data_key, iv = EXCLUDED.iv, tag = EXCLUDED.tag, data = EXCLUDED.data`; }, ); export const get = api( { method: "GET", path: "/vault/:tenant/:name", expose: false }, async ({ tenant, name }: { tenant: string; name: string }): Promise<{ value: string }> => { const row = await db.queryRow<{ data_key: Buffer; iv: Buffer; tag: Buffer; data: Buffer }>` SELECT data_key, iv, tag, data FROM tokens WHERE tenant = ${tenant} AND name = ${name}`; if (!row) throw APIError.notFound("no such entry"); const { Plaintext } = await kms.send( new DecryptCommand({ CiphertextBlob: row.data_key, EncryptionContext: { tenant, table: "tokens" } }), ); const decipher = createDecipheriv("aes-256-gcm", Plaintext!, row.iv); decipher.setAuthTag(row.tag); const value = Buffer.concat([decipher.update(row.data), decipher.final()]).toString("utf8"); Plaintext!.fill(0); return { value }; }, );

Set the key ID with encore secret set --type dev,prod KmsKeyId, and install the client with npm install @aws-sdk/client-kms. Encore provisions an IAM role for the service. Grant that role kms:GenerateDataKey and kms:Decrypt, and scope the grant to this key. Add an auth handler before exposing these endpoints beyond internal callers. Locally you need AWS credentials in your shell and a KMS key you can use for development, or you can stub the two KMS calls in tests. Encore secret values are not stored in the repository or in git.

A coding agent can add a new encrypted field in the same change as its column and test the round trip against a development KMS key, with the database provisioned by encore run.

Best fit: TypeScript teams on AWS that need to protect tokens or personal data at rest with keys they control, and keep ciphertext in their own Postgres database.

Frequently asked questions

What is envelope encryption?

Envelope encryption encrypts data with a data key, then encrypts that data key with a master key held in a key management service. You store the encrypted data key next to the ciphertext, and only the key management service can unwrap it, so large data never has to travel to KMS.

Why not encrypt data directly with KMS?

The KMS Encrypt API accepts at most 4 KB of plaintext and each call is a network request with its own cost and rate limit. Encrypting locally with a data key is faster for larger payloads and keeps the KMS key itself out of your application's memory.

What is the encryption context in AWS KMS?

It is a set of non-secret key-value pairs, such as the tenant ID or table name, that you pass when generating and decrypting a data key. KMS binds it cryptographically, so decryption fails if the context differs, and it appears in CloudTrail logs for auditing.

How do I use envelope encryption in an Encore service?

Call KMS from the service with the AWS SDK for JavaScript, encrypt with Node's crypto module and store the encrypted data key and ciphertext in the service's Encore Postgres database. The role your service runs under in AWS needs permission to call GenerateDataKey and Decrypt on the key.

Deploy to your cloud on AWS and Google Cloud
without managing infrastructure

Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.

~/orders — claude
Claude Code
Claude Code v2.1.180Opus 5.5~/orders