Encrypt for several recipients
Encrypt a payload once in a JWE JSON object and let several recipients open it, each with its own key.
A compact token has room for one recipient. The JSON serialization (RFC 7516 §7.2) locks the content once with a random content key, then locks a copy of that key for each recipient with that recipient's own key and algorithm. Think of one box with several padlocked key pouches hanging off it: whoever opens any pouch opens the box. encryptMulti builds that object and decryptMulti opens it with whichever recipient your key fits.
#Before you start
- These functions work on objects, not strings:
JSON.stringifythe result to send it andJSON.parseit before decrypting. Compact tokens go throughencryptanddecrypt. - Every recipient key is a JWK with an
algand, ideally, akid. ACryptoKeycan't be a recipient here. dirand bareECDH-ESare refused: both make the recipient's own key the content key, which can't be shared with anyone else. UseECDH-ES+A*KW,RSA-OAEP-256orA*KWinstead.- An object carries at most 16 recipients by default (
limits.recipients), and one call spends at most 16 key tries across all of them (limits.keyAttempts).
#Encrypt an incident report for three teams
import { encryptMulti, decryptMulti } from "unjwt/jwe";
import type { JWEDecryptJWK, JWEEncryptJWK, JWEGeneralSerialization } from "unjwt/jwe";
export interface IncidentReport {
incidentId: string;
summary: string;
}
/** Encrypt one report once, readable by the security team, legal and the offline archive. */
export function sealIncident(
report: IncidentReport,
recipients: { security: JWEEncryptJWK; legal: JWEEncryptJWK; archive: JWEEncryptJWK },
) {
return encryptMulti(
report,
[
{ key: recipients.security },
{ key: recipients.legal },
{ key: recipients.archive, header: { "x-retention": "7y" } },
],
{ aad: `incident:${report.incidentId}`, expiresIn: "90D" },
);
}
/** Each reader opens the same object with its own private key. */
export async function readIncident(sealed: JWEGeneralSerialization, myKey: JWEDecryptJWK) {
const { payload } = await decryptMulti<IncidentReport>(sealed, myKey);
return payload;
}- Three kinds of key, one ciphertext: security holds an
ECDH-ES+A256KWpair, legal anRSA-OAEP-256pair, and the archive a sharedA256KWkey. Each recipient entry records its ownalgandkid. headeradds members to one recipient's entry, here a retention hint for the archive. Recipient headers are not integrity protected: anyone can change them, so never base an access decision on them.aadbinds the ciphertext to context outside it, here the incident ID (RFC 7516 §5.1). It travels in the object asaad, and changing it makes every recipient fail to open.readIncidentreturns the payload to whichever recipient's private key you pass.decryptMultialso tells you which entry opened asrecipientIndex, with its header asrecipientHeader.
The object looks like this:
// {
// protected: "eyJlbmMiOiJBMjU2R0NNIiwidHlwIjoiSldUIn0", // { enc: "A256GCM", typ: "JWT" }
// recipients: [
// { header: { kid: "security-2026-10", epk: {…}, alg: "ECDH-ES+A256KW" }, encrypted_key: "x1rI…" },
// { header: { kid: "legal-2026-10", alg: "RSA-OAEP-256" }, encrypted_key: "ddS6…" },
// { header: { kid: "archive-2026", "x-retention": "7y", alg: "A256KW" }, encrypted_key: "Uf-v…" },
// ],
// aad: "aW5jaWRlbnQ6aW5jXzMxMDc",
// iv: "4yB7…", ciphertext: "AKr5…", tag: "kfTI…",
// }#Know the three header tiers
| Tier | Set with | Holds | Integrity protected |
|---|---|---|---|
protected | protectedHeader | enc, typ, your members | yes |
unprotected | sharedUnprotectedHeader | members shared by every recipient | no |
recipients[].header | a recipient's header | alg, kid, epk, p2s, p2c, iv, tag, your members | no |
- A name lives in one tier only (RFC 7516 §7.2.1). Setting
kidinsharedUnprotectedHeaderand also on a recipient throwsERR_JWE_HEADER_PARAMS_NOT_DISJOINT. critbelongs in the protected tier; elsewhere it throwsERR_INVALID_OPTION.zipandepkare refused in every tier.encis read from the protected or shared tier, never from a recipient's header.typchecks (options.typ) read the protected tier only.protectedHeaderin the result is only what was protected;encryptMultiwritesalgper recipient, so read it fromrecipientHeader.
#Open the object
decryptMulti(jwe, key, options) tries the recipients in order and returns the first your key opens, with every decrypt check applied. The recipients list isn't covered by the authentication tag, so anyone can add or rewrite entries; a failure scoped to one recipient (a bad header, a disallowed alg, a key that doesn't fit) only moves on to the next. A failure of the whole object (the protected header, the shared header, the content segments, the claims) is thrown at once.
When none of two or more recipients opens, decryptMulti throws ERR_JWE_DECRYPTION_FAILED, and its cause holds one JWTError per recipient, in order, so you can see why each one failed:
const error = await decryptMulti(sealed, { keys: [otherKey] }).catch((e) => e);
error.code; // "ERR_JWE_DECRYPTION_FAILED"
error.cause.map((entry) => entry.code); // ["ERR_JWE_ALG_NOT_ALLOWED", "ERR_JWE_ALG_NOT_ALLOWED", "ERR_JWK_KEY_NOT_FOUND"]An object with a single recipient throws that recipient's own error instead, the same code decrypt gives for the same failure.
strictRecipientMatch: true tries only the recipients your key could open, judged by key type, size and curve; a kid on a single key never rules it out. When none fits, it throws ERR_JWE_NO_MATCHING_RECIPIENT without trying any. When it tried some and none opened, a recipient it skipped shows as ERR_JWE_NO_MATCHING_RECIPIENT in its slot of cause.
#Send one recipient as Flattened JSON
encryptMulti always returns the General form, even for one recipient. generalToFlattened lifts a single recipient's header and encrypted_key to the top level, the shape some consumers expect, and throws ERR_JWE_INVALID_SERIALIZATION for any other count. decryptMulti accepts both.
const flat = generalToFlattened(await encryptMulti(report, [{ key: archiveKey }]));
Object.keys(flat); // ["protected", "iv", "ciphertext", "tag", "header", "encrypted_key"]#Limits
| Limit | Default | Over the limit |
|---|---|---|
limits.recipients | 16 | ERR_JWE_INVALID before any recipient is read. |
limits.keyCandidates | 8 | That recipient fails with ERR_JWK_KEY_NOT_FOUND: more JWK Set entries fit it. |
limits.keyAttempts | 16 | ERR_JWK_KEY_NOT_FOUND, and no later recipient is tried. |
limits.pbes2Iterations | 2_400_000 | The recipient that would exceed it fails with ERR_JWE_INVALID. |
limits.keyAttempts is one budget for the whole call: every unwrap against a candidate key spends one, summed across all recipients. A single key spends one per recipient it's tried on, and a JWK Set whose kid matches spends one per recipient too. An object of ten recipients without kid, opened with a set of two keys, needs twenty tries and runs out. limits.pbes2Iterations is likewise shared, so a pile of injected PBES2 recipients can't multiply the work. Give keys a kid, or pass strictRecipientMatch.
#When it fails
| Situation | What happens |
|---|---|
| No recipients | encryptMulti throws ERR_JWE_INVALID. |
A recipient key that isn't a JWK, or a JWK without alg | encryptMulti throws ERR_JWE_RECIPIENT_ALG_INFERENCE. |
A recipient resolves to dir or bare ECDH-ES | encryptMulti throws ERR_JWE_ALG_FORBIDDEN_IN_MULTI. |
| A name in more than one header tier | Throws ERR_JWE_HEADER_PARAMS_NOT_DISJOINT. |
crit outside the protected tier, zip or epk anywhere, an aad that isn't text or bytes, or any encrypt option rule | encryptMulti throws ERR_INVALID_OPTION. |
A claim option with a non-JSON payload or with validateClaims: false | decryptMulti throws ERR_INVALID_OPTION, before the token is read. |
A string instead of an object, or recipients mixed with a top-level header or encrypted_key | Throws ERR_JWE_INVALID_SERIALIZATION. |
More recipients than limits.recipients | Throws ERR_JWE_INVALID. |
| The key-attempt budget ran out | Throws ERR_JWK_KEY_NOT_FOUND. |
| None of two or more recipients opens | Throws ERR_JWE_DECRYPTION_FAILED with one error per recipient as cause. |
| The only recipient fails | Throws that recipient's own error, as decrypt does. |
strictRecipientMatch found no recipient the key could open | Throws ERR_JWE_NO_MATCHING_RECIPIENT. |
| The payload or claims fail after decryption | Throws the decrypt code, such as ERR_JWT_EXPIRED. |
Handle errors lists every code and what to do about it.
#Options
encryptMulti(payload, recipients, options) takes the encrypt options that apply to the whole object: enc (default A256GCM), protectedHeader, the time options (object payloads only, as on encrypt), cek and contentEncryptionIV. Per-recipient settings move onto each recipient: { key, header?, p2s?, p2c?, keyManagementIV?, ecdh? }. Two options are its own:
| Option | Default | Notes |
|---|---|---|
sharedUnprotectedHeader | none | Members for every recipient, written as unprotected. Not protected. |
aad | none | Text or bytes bound to the ciphertext. Empty means none. |
decryptMulti(jwe, key, options) takes every decrypt option, plus:
| Option | Default | Notes |
|---|---|---|
limits.recipients | 16 | Most recipients one object may carry. |
limits.keyAttempts | 16 | Key tries one call may run, summed across recipients. |
strictRecipientMatch | false | Try only the recipients the key could open. |
#Going further
- One recipient: Encrypt a payload.
- Which key management algorithm each recipient uses: Choose encryption algorithms.
- Several signers instead of several recipients: Sign for several verifiers.