Wrap and unwrap keys

Store a key encrypted under another key and get it back when you need it, or agree on a shared key with another service.

Wrapping is putting one key in a locked envelope that only a second key opens. The key inside is the one you use day to day, such as a tenant's signing secret; the key that locks the envelope, often called the master key or key-encryption key, stays in your secret store. Your database then holds only envelopes, so a leaked backup reveals nothing without the master key. This is the same step a JWE runs on its content key, and encrypt() and decrypt() do it for you; call wrapKey and unwrapKey yourself when you store keys, not tokens.

#Before you start

  • Wrapping takes the raw bytes of a key, or a CryptoKey, and returns bytes. It does not keep the key's kid or alg, so store those next to the envelope.
  • The master key is a secret for A*KW or A*GCMKW, or a key pair for RSA-OAEP* and ECDH-ES*. Generate it with generateJWK, which stamps the algorithm you name.
  • AES Key Wrap (A*KW) wraps keys of 16 bytes or more, in whole 8-byte blocks. Every secret generateJWK makes fits.

#Store a tenant's key under a master key

Each tenant gets its own HS256 secret, and the database keeps it wrapped under one A256KW master key:

tenant-keys.ts
import { importKey, unwrapKey, wrapKey, type JWK_oct } from "unjwt/jwk";
import { base64UrlParse, base64UrlStringify } from "unjwt/utils";

const raw = process.env.MASTER_KEY; // an A256KW JWK from generateJWK("A256KW")
if (!raw) throw new Error("MASTER_KEY is not set");
const masterKey: JWK_oct<"A256KW"> = JSON.parse(raw);

/** The form you store in the tenant's row: the wrapped bytes, plus the `kid` in clear. */
export interface SealedKey {
  kid: string;
  wrapped: string;
}

export async function sealTenantKey(tenantKey: JWK_oct<"HS256">): Promise<SealedKey> {
  if (!tenantKey.kid) throw new Error("A tenant key needs a kid");
  const secret = await importKey(tenantKey);
  const { encryptedKey } = await wrapKey(secret, masterKey, { alg: "A256KW" });
  return { kid: tenantKey.kid, wrapped: base64UrlStringify(encryptedKey) };
}

export async function openTenantKey(sealed: SealedKey): Promise<JWK_oct<"HS256">> {
  const encryptedKey = base64UrlParse(sealed.wrapped, { returnAs: "bytes" });
  const secret = await unwrapKey(encryptedKey, masterKey, { alg: "A256KW", format: "raw" });
  return { kty: "oct", k: base64UrlStringify(secret), alg: "HS256", kid: sealed.kid };
}
  • importKey(tenantKey): an oct JWK imports as its raw bytes, which is what wrapKey takes.
  • The envelope: encryptedKey is 8 bytes longer than the key inside. Base64url turns it into text a database column holds.
  • format: "raw": unwrapKey returns a CryptoKey by default; "raw" gives the bytes back, ready to rebuild the JWK.
  • The wrong master key: unwrapping with another key, or a damaged envelope, throws ERR_JWE_DECRYPTION_FAILED and never returns wrong bytes.

#Pick a wrapping algorithm

algMaster keywrapKey returnsWhat unwrapKey needs back
A128KW, A192KW, A256KWan oct secret{ encryptedKey }nothing more
A128GCMKW … A256GCMKWan oct secret{ encryptedKey, iv, tag }iv, tag
RSA-OAEP, RSA-OAEP-256 … -512public key wraps, private key unwraps{ encryptedKey }nothing more
ECDH-ES+A128KW … +A256KWpublic key wraps, private key unwraps{ encryptedKey, epk, apu?, apv? }epk, and apu/apv when set
PBES2-*a password{ encryptedKey, p2s, p2c }p2s, p2c

A256KW with a secret master key is the plain choice for keys you store yourself. A key pair fits when one service wraps and another unwraps: the wrapping side holds only the public key, so it can seal envelopes it cannot open. Store every returned member alongside encryptedKey; iv, tag, p2s, apu and apv come back as base64url text, epk as a public JWK.

dir and bare ECDH-ES wrap nothing: they return an empty encryptedKey, because in a JWE the key itself or the agreed secret is the content key.

#Derive a shared secret

Two services that each hold an ECDH-ES key pair can arrive at the same secret without either one sending it. Each side combines its own private key with the other side's public key; ECDH followed by the Concat KDF (RFC 7518 §4.6) gives both the same bytes. Here a billing service and an API service turn that secret into an A256GCM key for tokens they send each other:

shared-secret.ts
import {
  deriveSharedSecret,
  type JWK_EC_Private,
  type JWK_EC_Public,
  type JWK_oct,
} from "unjwt/jwk";
import { base64UrlStringify } from "unjwt/utils";

const encoder = new TextEncoder();
// The same two labels on both sides, in the same order.
const partyUInfo = encoder.encode("billing.example.com");
const partyVInfo = encoder.encode("api.example.com");

/** Each service passes its own private key and the other service's public key. */
export async function channelKey(
  ownKey: JWK_EC_Private<"ECDH-ES">,
  peerKey: JWK_EC_Public<"ECDH-ES">,
): Promise<JWK_oct<"A256GCM">> {
  const secret = await deriveSharedSecret(peerKey, ownKey, {
    enc: "A256GCM",
    partyUInfo,
    partyVInfo,
  });
  return { kty: "oct", k: base64UrlStringify(secret), alg: "A256GCM", kid: "billing-api" };
}
  • The arguments: deriveSharedSecret(publicKey, privateKey, options), the other side's public key first. Billing calls channelKey(billingPrivate, apiPublic), the API channelKey(apiPrivate, billingPublic), and both get the same JWK.
  • The keys: two EC key pairs from generateJWK("ECDH-ES"), on the same curve. deriveSharedSecret takes X25519 pairs the same way, from generateJWK("ECDH-ES", { namedCurve: "X25519" }) and typed JWK_OKP_Private / JWK_OKP_Public. A key generated for ES256 is refused, and so is one for ECDH-ES+A256KW unless enc is that same value.
  • enc: the algorithm the secret is for. It's mixed into the derivation and sets the length: 256 bits for A256GCM. A content encryption algorithm or an ECDH-ES+A*KW value both work; bare "ECDH-ES" needs keyLength.
  • partyUInfo and partyVInfo: labels mixed into the derivation, so the same two pairs give a different secret for another purpose. Both sides pass the same bytes in the same order.
  • The same secret every time: the two pairs always give the same bytes. Rotating either pair is the only way to change it, and anyone who later obtains one private key can derive it too.

Use it when both sides keep long-lived pairs and want a key for their own protocol, or one shared key for many tokens. To encrypt a token for someone, use encrypt() with their public key and ECDH-ES: it agrees with a fresh key of its own for every token and writes the public half into the header as epk, so each token gets its own secret and you hold no private key on the sending side.

#When it fails

SituationWhat happens
The unwrap runs and doesn't succeed: wrong key, damaged encryptedKey, forged tagThrows ERR_JWE_DECRYPTION_FAILED, the same for every cause (RFC 7516 §11.5).
iv/tag, p2s/p2c or epk is missing on unwrapThrows ERR_JWE_INVALID.
An incoming p2c is outside minIterations to maxIterationsThrows ERR_JWE_INVALID.
A private key passed to wrapKey, or a string under anything but PBES2-*Throws ERR_JWK_INVALID.
The master key's alg differs from the alg you passThrows ERR_JWK_INVALID.
Bare ECDH-ES without ecdh.encThrows ERR_JWK_INVALID.
The key to wrap doesn't fit AES Key Wrap, p2s is under 8 bytes, p2c is outside 1000 to 600 000, or partyUInfo/partyVInfo is over 1024 bytesThrows ERR_INVALID_OPTION.
wrappedKey isn't bytes, or options isn't an objectThrows ERR_INVALID_OPTION.

| deriveSharedSecret gets an RSA, oct or ES* key, a key whose alg is neither ECDH-ES nor enc, or the wrong half in either place | Throws ERR_JWK_INVALID. | | deriveSharedSecret gets keys on two different curves | Throws ERR_JWK_INVALID, with the platform's error as cause. | | deriveSharedSecret with enc: "ECDH-ES" and no keyLength | Throws ERR_JWK_INVALID. | | keyLength isn't a positive multiple of 8 up to 8192 | Throws ERR_INVALID_OPTION. | | enc is neither a content encryption algorithm nor an ECDH-ES* value | Throws ERR_JWE_INVALID. |

Handle errors lists every code.

#Options

wrapKey(keyToWrap, wrappingKey, options):

OptionDefaultNotes
algrequiredThe wrapping algorithm.
p2s, p2crequired for PBES2-*Salt of 8 bytes or more; iteration count from 1000 to 600 000.
ivrandomA*GCMKW. Leave it out: reusing an IV under the same key breaks AES-GCM.
ecdh.ephemeralKeya fresh key on the recipient's curveECDH-ES*. Leave it out outside known-answer tests.
ecdh.partyUInfo, ecdh.partyVInfononeECDH-ES*. Agreement info mixed into the derivation, up to 1024 bytes each.
ecdh.encnoneRequired for bare ECDH-ES.

unwrapKey(wrappedKey, unwrappingKey, options):

OptionDefaultNotes
algrequiredThe algorithm the key was wrapped with.
format"cryptokey""raw" returns a Uint8Array.
iv, tagnoneA*GCMKW, as wrapKey returned them.
p2s, p2cnonePBES2-*, as wrapKey returned them.
minIterations, maxIterations1000, 600_000Bounds on p2c.
epk, apu, apv, encnoneECDH-ES*. enc is required for bare ECDH-ES.
unwrappedKeyAlgorithm, keyUsage, extractableAES-GCM, ["encrypt", "decrypt"], trueHow the key is imported with format: "cryptokey".

deriveSharedSecret(publicKey, privateKey, options) returns a Uint8Array:

OptionDefaultNotes
encrequiredA content encryption algorithm, or ECDH-ES/ECDH-ES+A*KW. Mixed into the derivation.
keyLengththe length of encIn bits. Required for "ECDH-ES".
partyUInfo, partyVInfononeBytes mixed into the derivation; both sides pass the same.

#Going further

  • Store a whole JWK, members and all: encrypt it as a token with encrypt(); the JWE carries the key and you skip rebuilding it.
  • Wrap one key for several recipients: Encrypt for several recipients.
  • A password instead of a master key: Derive keys from a password.
  • Rotate the master key: unwrap each envelope with the old key and wrap it again with the new one; keep the old key until every row is rewritten.