
# 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](https://www.rfc-editor.org/rfc/rfc7516#section-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`](/jwe/encrypt) and [`decrypt`](/jwe/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

<!-- automd:region src="../../examples/jwe/multi-recipient.ts" -->

```ts [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;
}
```

<!-- /automd -->

- **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](https://www.rfc-editor.org/rfc/rfc7516#section-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:

```ts
// {
//   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](https://www.rfc-editor.org/rfc/rfc7516#section-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`](/jwe/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:

```ts
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`](/jwe/decrypt#when-it-fails) 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.

```ts
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](/jwe/encrypt#options) 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](/jwe/decrypt#when-it-fails), such as `ERR_JWT_EXPIRED`. |

[Handle errors](/safety/errors) lists every code and what to do about it.

## Options

`encryptMulti(payload, recipients, options)` takes the [`encrypt` options](/jwe/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](/jwe/decrypt#options), 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](/jwe/encrypt).
- **Which key management algorithm each recipient uses**: [Choose encryption algorithms](/jwe/algorithms).
- **Several signers instead of several recipients**: [Sign for several verifiers](/jws/multi).
