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.stringify the result to send it and JSON.parse it before decrypting. Compact tokens go through encrypt and decrypt.
  • Every recipient key is a JWK with an alg and, ideally, a kid. A CryptoKey can't be a recipient here.
  • dir and bare ECDH-ES are refused: both make the recipient's own key the content key, which can't be shared with anyone else. Use ECDH-ES+A*KW, RSA-OAEP-256 or A*KW instead.
  • 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

multi-recipient.ts
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+A256KW pair, legal an RSA-OAEP-256 pair, and the archive a shared A256KW key. Each recipient entry records its own alg and kid.
  • header adds 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.
  • aad binds the ciphertext to context outside it, here the incident ID (RFC 7516 §5.1). It travels in the object as aad, and changing it makes every recipient fail to open.
  • readIncident returns the payload to whichever recipient's private key you pass. decryptMulti also tells you which entry opened as recipientIndex, with its header as recipientHeader.

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

TierSet withHoldsIntegrity protected
protectedprotectedHeaderenc, typ, your membersyes
unprotectedsharedUnprotectedHeadermembers shared by every recipientno
recipients[].headera recipient's headeralg, kid, epk, p2s, p2c, iv, tag, your membersno
  • A name lives in one tier only (RFC 7516 §7.2.1). Setting kid in sharedUnprotectedHeader and also on a recipient throws ERR_JWE_HEADER_PARAMS_NOT_DISJOINT.
  • crit belongs in the protected tier; elsewhere it throws ERR_INVALID_OPTION. zip and epk are refused in every tier.
  • enc is read from the protected or shared tier, never from a recipient's header.
  • typ checks (options.typ) read the protected tier only.
  • protectedHeader in the result is only what was protected; encryptMulti writes alg per recipient, so read it from recipientHeader.

#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

LimitDefaultOver the limit
limits.recipients16ERR_JWE_INVALID before any recipient is read.
limits.keyCandidates8That recipient fails with ERR_JWK_KEY_NOT_FOUND: more JWK Set entries fit it.
limits.keyAttempts16ERR_JWK_KEY_NOT_FOUND, and no later recipient is tried.
limits.pbes2Iterations2_400_000The 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

SituationWhat happens
No recipientsencryptMulti throws ERR_JWE_INVALID.
A recipient key that isn't a JWK, or a JWK without algencryptMulti throws ERR_JWE_RECIPIENT_ALG_INFERENCE.
A recipient resolves to dir or bare ECDH-ESencryptMulti throws ERR_JWE_ALG_FORBIDDEN_IN_MULTI.
A name in more than one header tierThrows 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 ruleencryptMulti throws ERR_INVALID_OPTION.
A claim option with a non-JSON payload or with validateClaims: falsedecryptMulti 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_keyThrows ERR_JWE_INVALID_SERIALIZATION.
More recipients than limits.recipientsThrows ERR_JWE_INVALID.
The key-attempt budget ran outThrows ERR_JWK_KEY_NOT_FOUND.
None of two or more recipients opensThrows ERR_JWE_DECRYPTION_FAILED with one error per recipient as cause.
The only recipient failsThrows that recipient's own error, as decrypt does.
strictRecipientMatch found no recipient the key could openThrows ERR_JWE_NO_MATCHING_RECIPIENT.
The payload or claims fail after decryptionThrows 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:

OptionDefaultNotes
sharedUnprotectedHeadernoneMembers for every recipient, written as unprotected. Not protected.
aadnoneText or bytes bound to the ciphertext. Empty means none.

decryptMulti(jwe, key, options) takes every decrypt option, plus:

OptionDefaultNotes
limits.recipients16Most recipients one object may carry.
limits.keyAttempts16Key tries one call may run, summed across recipients.
strictRecipientMatchfalseTry only the recipients the key could open.

#Going further