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'skidoralg, so store those next to the envelope. - The master key is a secret for
A*KWorA*GCMKW, or a key pair forRSA-OAEP*andECDH-ES*. Generate it withgenerateJWK, which stamps the algorithm you name. - AES Key Wrap (
A*KW) wraps keys of 16 bytes or more, in whole 8-byte blocks. Every secretgenerateJWKmakes 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:
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): anoctJWK imports as its raw bytes, which is whatwrapKeytakes.- The envelope:
encryptedKeyis 8 bytes longer than the key inside. Base64url turns it into text a database column holds. format: "raw":unwrapKeyreturns aCryptoKeyby 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_FAILEDand never returns wrong bytes.
#Pick a wrapping algorithm
alg | Master key | wrapKey returns | What unwrapKey needs back |
|---|---|---|---|
A128KW, A192KW, A256KW | an oct secret | { encryptedKey } | nothing more |
A128GCMKW … A256GCMKW | an oct secret | { encryptedKey, iv, tag } | iv, tag |
RSA-OAEP, RSA-OAEP-256 … -512 | public key wraps, private key unwraps | { encryptedKey } | nothing more |
ECDH-ES+A128KW … +A256KW | public 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:
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 callschannelKey(billingPrivate, apiPublic), the APIchannelKey(apiPrivate, billingPublic), and both get the same JWK. - The keys: two EC key pairs from
generateJWK("ECDH-ES"), on the same curve.deriveSharedSecrettakes X25519 pairs the same way, fromgenerateJWK("ECDH-ES", { namedCurve: "X25519" })and typedJWK_OKP_Private/JWK_OKP_Public. A key generated forES256is refused, and so is one forECDH-ES+A256KWunlessencis that same value. enc: the algorithm the secret is for. It's mixed into the derivation and sets the length: 256 bits forA256GCM. A content encryption algorithm or anECDH-ES+A*KWvalue both work; bare"ECDH-ES"needskeyLength.partyUInfoandpartyVInfo: 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
| Situation | What happens |
|---|---|
The unwrap runs and doesn't succeed: wrong key, damaged encryptedKey, forged tag | Throws ERR_JWE_DECRYPTION_FAILED, the same for every cause (RFC 7516 §11.5). |
iv/tag, p2s/p2c or epk is missing on unwrap | Throws ERR_JWE_INVALID. |
An incoming p2c is outside minIterations to maxIterations | Throws 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 pass | Throws ERR_JWK_INVALID. |
Bare ECDH-ES without ecdh.enc | Throws 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 bytes | Throws ERR_INVALID_OPTION. |
wrappedKey isn't bytes, or options isn't an object | Throws 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):
| Option | Default | Notes |
|---|---|---|
alg | required | The wrapping algorithm. |
p2s, p2c | required for PBES2-* | Salt of 8 bytes or more; iteration count from 1000 to 600 000. |
iv | random | A*GCMKW. Leave it out: reusing an IV under the same key breaks AES-GCM. |
ecdh.ephemeralKey | a fresh key on the recipient's curve | ECDH-ES*. Leave it out outside known-answer tests. |
ecdh.partyUInfo, ecdh.partyVInfo | none | ECDH-ES*. Agreement info mixed into the derivation, up to 1024 bytes each. |
ecdh.enc | none | Required for bare ECDH-ES. |
unwrapKey(wrappedKey, unwrappingKey, options):
| Option | Default | Notes |
|---|---|---|
alg | required | The algorithm the key was wrapped with. |
format | "cryptokey" | "raw" returns a Uint8Array. |
iv, tag | none | A*GCMKW, as wrapKey returned them. |
p2s, p2c | none | PBES2-*, as wrapKey returned them. |
minIterations, maxIterations | 1000, 600_000 | Bounds on p2c. |
epk, apu, apv, enc | none | ECDH-ES*. enc is required for bare ECDH-ES. |
unwrappedKeyAlgorithm, keyUsage, extractable | AES-GCM, ["encrypt", "decrypt"], true | How the key is imported with format: "cryptokey". |
deriveSharedSecret(publicKey, privateKey, options) returns a Uint8Array:
| Option | Default | Notes |
|---|---|---|
enc | required | A content encryption algorithm, or ECDH-ES/ECDH-ES+A*KW. Mixed into the derivation. |
keyLength | the length of enc | In bits. Required for "ECDH-ES". |
partyUInfo, partyVInfo | none | Bytes 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.