
# Decrypt a token

> Open a compact JWE with a key, a JWK Set, a lookup function or a password, check its header and claims, and get the payload back.

`decrypt(token, key, options)` unlocks the content key, opens the content, and checks the claims, in that order. A wrong key, a wrong password and a tampered token all end in the same `ERR_JWE_DECRYPTION_FAILED`, so the error can't be used to probe which part was wrong ([RFC 7516 §11.5](https://www.rfc-editor.org/rfc/rfc7516#section-11.5)). Everything the header decides, such as the algorithms, `zip`, `crit` and `typ`, is settled before any key is touched.

## Before you start

- The decryption key: the **private** half of the key pair the sender encrypted for, the shared key, or the password. A public JWK here throws `ERR_JWK_INVALID`.
- Private keys must survive restarts: store them as JWK JSON in your secret store and load them at start-up, all the ones still in use, as a [JWK Set](/jwk/sets).
- Know which `alg` and `enc` your senders use, and pin them. The token's header names its own algorithms, and whoever made the token wrote that header.
- `decrypt` checks `aud` only when you pass `audience`, and a token without `exp` never expires unless you require it.

## Open records with a keyring

The reporting service holds its current and previous private keys as a JWK Set, so tokens sealed before a rotation still open:

<!-- automd:region src="../../examples/jwe/decrypt-with-keyring.ts" -->

```ts [decrypt-with-keyring.ts]
import { decrypt } from "unjwt/jwe";
import type { JWKSet } from "unjwt/jwk";
import { isJWKSet } from "unjwt/utils";

const raw = process.env.REPORTS_DECRYPTION_KEYS;
if (!raw) throw new Error("REPORTS_DECRYPTION_KEYS is not set");
const keyring: JWKSet = JSON.parse(raw);
if (!isJWKSet(keyring)) throw new Error("REPORTS_DECRYPTION_KEYS must be a JWK Set");

export interface CustomerRecord {
  customerId: string;
  email: string;
  country: string;
}

/** Open a sealed customer record with whichever private key in the keyring its `kid` names. */
export async function openCustomer(token: string) {
  const { payload } = await decrypt<CustomerRecord>(token, keyring, {
    algorithms: ["ECDH-ES+A256KW"],
    encryptionAlgorithms: ["A256GCM"],
    requiredClaims: ["exp"],
  });
  return payload;
}
```

<!-- /automd -->

- **A JWK Set**: the header's `kid` picks the private key. A `kid` the set doesn't hold throws `ERR_JWK_KEY_NOT_FOUND` before any decryption.
- **`algorithms` and `encryptionAlgorithms`**: the only key management and content algorithms this service accepts. Anything else is `ERR_JWE_ALG_NOT_ALLOWED`.
- **`requiredClaims: ["exp"]`**: a record sealed without an expiry is refused.

## Pass the key

| Key                                            | When to use it                                                                                                                                            |
| ---------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- |
| A private JWK                                  | One recipient, one key pair (`RSA-OAEP*`, `ECDH-ES*`).                                                                                                    |
| An `oct` JWK                                   | A shared key (`A*KW`, `A*GCMKW`) or a `dir` content key.                                                                                                  |
| A password string                              | PBES2 tokens only; any other `alg` is refused.                                                                                                            |
| A `CryptoKey` or raw bytes                     | Keys you already hold in that form. Bytes declare no algorithm: pass `algorithms`.                                                                        |
| A JWK Set (`{ keys: [...] }`)                  | Rotation, several keys. See [Use a JWK Set](/jwk/sets).                                                                                                   |
| A lookup function `({ header, token }) => key` | Keys in a database or a vault. It receives the token's protected header and the token, and may return any of the above, a JWK Set or a password included. |

The JWK Set rules match [`verify`](/jws/verify#pass-the-key): the `kid` narrows the candidates, a token without `kid` is tried against every entry whose `alg`, `use` (`"enc"`) and `key_ops` fit, up to `limits.keyCandidates` (8). When no candidate opens it, `ERR_JWE_DECRYPTION_FAILED` carries one error per candidate tried as its `cause`. A lookup function answers as on `verify`: the key, a JWK Set, or `undefined` when it has none for the token, which throws `ERR_JWK_KEY_NOT_FOUND`. Throw when the lookup can't answer: a `JWTError` it throws reaches you as it is, and any other error is `ERR_JWK_KEY_NOT_FOUND`, with your error as `cause`.

## Restrict the algorithms

Two lists decide what opens:

- **`algorithms`** for the key management `alg`. Without it, a JWK that declares `alg` accepts that one only (an `oct` JWK declared as a content algorithm accepts `dir`), a password accepts the three `PBES2-*` algorithms, and an EC or `X25519` key without `alg` accepts the four `ECDH-ES*`. Raw bytes declare nothing: `decrypt` refuses rather than guess, with `ERR_JWE_ALG_NOT_ALLOWED`.
- **`encryptionAlgorithms`** for the content `enc`. Without it, every supported `enc` is accepted.

An AES `CryptoKey` admits only its key-wrapping algorithm: an AES-GCM key `A*GCMKW`, an AES-KW key `A*KW`. A token made with that AES-GCM key under `dir` opens only with `algorithms: ["dir"]`; [Encrypt a payload](/jwe/encrypt#use-an-aes-cryptokey) explains why.

```ts
await decrypt(token, rawKeyBytes);
// JWTError ERR_JWE_ALG_NOT_ALLOWED: Cannot infer allowed algorithms from this key, pass "algorithms".
await decrypt(token, rawKeyBytes, { algorithms: ["A256KW"] }); // ok

await decrypt(token, key, { encryptionAlgorithms: ["A128GCM"] });
// JWTError ERR_JWE_ALG_NOT_ALLOWED: Content encryption algorithm not allowed: A256GCM
```

## Bound the work of a password

A PBES2 token carries its own iteration count (`p2c`) in the header, which the sender writes. A forged token could ask your server for billions of PBKDF2 rounds, so `decrypt` checks the count before deriving anything:

| Option                   | Default     | What it bounds                                                                                       |
| ------------------------ | ----------- | ---------------------------------------------------------------------------------------------------- |
| `minIterations`          | `1000`      | Lowest `p2c` accepted ([RFC 7518 §4.8.1.2](https://www.rfc-editor.org/rfc/rfc7518#section-4.8.1.2)). |
| `maxIterations`          | `600_000`   | Highest `p2c` one attempt may ask for. Raise it only for a sender that mints more.                   |
| `limits.pbes2Iterations` | `2_400_000` | Total PBKDF2 iterations one call may spend, summed over every attempt: four at the default count.    |

A count outside `minIterations` to `maxIterations`, or past the remaining budget, throws `ERR_JWE_INVALID` without deriving. When you only open tokens you made, pin `algorithms` to your one PBES2 variant and `maxIterations` to your own `p2c`, as [the password example](/jwe/encrypt#encrypt-with-a-password) does.

```ts
await decrypt(token, passphrase, { minIterations: 10_000 });
// JWTError ERR_JWE_INVALID: PBES2 "p2c" below the minimum of 10000 iterations (got 1000).
```

## Check the claims

Under the default `payload: "json"`, the claims are checked after decryption with the same options and codes as [`verify`](/jws/verify#check-the-claims): `audience`, `issuer`, `subject`, `maxTokenAge`, `requiredClaims`, `clockTolerance`, `currentDate`, `typ`, `recognizedHeaders`, `validateClaims`. [Validate claims](/safety/claims) goes through each. `audience`, `issuer`, `subject`, `maxTokenAge` and `requiredClaims` need those checks to run: with `validateClaims: false` or a `"string"` or `"bytes"` payload they throw `ERR_INVALID_OPTION`.

## Read a payload that is not JSON

You declare what the plaintext is with `payload`; the token never decides:

| `payload`           | You get                                        | Claims checked |
| ------------------- | ---------------------------------------------- | -------------- |
| omitted or `"json"` | the claims object, typed `decrypt<MyClaims>()` | yes            |
| `"string"`          | the plaintext as UTF-8 text                    | no             |
| `"bytes"`           | the plaintext as a `Uint8Array`                | no             |

```ts
const sealed = await encrypt("plain text", key);
await decrypt(sealed, key);
// JWTError ERR_JWE_INVALID: Invalid JWE: Payload is not a JSON object.
(await decrypt(sealed, key, { payload: "string" })).payload; // "plain text"
```

A [signed-then-encrypted token](/jwe/encrypt#sign-then-encrypt) holds a string, so it opens with `payload: "string"`.

## What you get back

```ts
const { payload, protectedHeader } = await decrypt<CustomerRecord>(token, keyring, options);
// payload:         { customerId: "cus_88f1", email: "ada@example.com", country: "IT", iat: 1792982291, exp: 1792982891 }
// protectedHeader: { kid: "2026-10", epk: {…}, alg: "ECDH-ES+A256KW", enc: "A256GCM", typ: "JWT" }
```

`protectedHeader` always carries `alg` and `enc`. With `returnCek: true` the result also holds `cek`, the raw content key, and `aad`, the bytes it authenticated; that's for test vectors and key escrow, and throws `ERR_INVALID_OPTION` when the content key can't be exported.

## When it fails

In the order `decrypt` checks:

| Situation                                                                                 | What happens                                                                                                                              |
| ----------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------- |
| An option is empty or malformed                                                           | Throws `ERR_INVALID_OPTION`, before the token is read.                                                                                    |
| A claim option with a non-JSON `payload` or with `validateClaims: false`                  | Throws `ERR_INVALID_OPTION`, before the token is read.                                                                                    |
| Not a string, not five segments, or a header without `alg` and `enc`                      | Throws `ERR_JWE_INVALID`.                                                                                                                 |
| `alg` is `"none"` or unsupported                                                          | Throws `ERR_JWE_ALG_NOT_ALLOWED`.                                                                                                         |
| `enc` is unsupported, or the header carries `zip`                                         | Throws `ERR_JWE_INVALID`.                                                                                                                 |
| `enc` is not in `encryptionAlgorithms`                                                    | Throws `ERR_JWE_ALG_NOT_ALLOWED`.                                                                                                         |
| `crit` names an extension you didn't list, `typ` doesn't match, or a segment is malformed | Throws `ERR_JWE_INVALID`.                                                                                                                 |
| The lookup function returned `undefined`                                                  | Throws `ERR_JWK_KEY_NOT_FOUND`.                                                                                                           |
| The lookup function threw an error that is not a `JWTError`                               | Throws `ERR_JWK_KEY_NOT_FOUND`, with that error as `cause`.                                                                               |
| The lookup function threw a `JWTError`                                                    | Throws that error.                                                                                                                        |
| `alg` is not in `algorithms`, or nothing can be inferred from the key                     | Throws `ERR_JWE_ALG_NOT_ALLOWED`.                                                                                                         |
| The JWK Set has no entry for the `kid`, or more candidates than `limits.keyCandidates`    | Throws `ERR_JWK_KEY_NOT_FOUND`.                                                                                                           |
| A PBES2 count outside the bounds or past the budget                                       | Throws `ERR_JWE_INVALID`.                                                                                                                 |
| No key, a public key, a password under a non-PBES2 `alg`, or a key in the wrong role      | Throws `ERR_JWK_INVALID`.                                                                                                                 |
| Wrong key, wrong password, or a changed token                                             | Throws `ERR_JWE_DECRYPTION_FAILED`.                                                                                                       |
| The plaintext doesn't fit the `payload` mode                                              | Throws `ERR_JWE_INVALID`.                                                                                                                 |
| A claim check fails                                                                       | Throws `ERR_JWT_CLAIM_MISSING`, `ERR_JWT_CLAIM_INVALID`, `ERR_JWT_NBF` or `ERR_JWT_EXPIRED`, as on [`verify`](/jws/verify#when-it-fails). |

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

## Options

Every claim option of [`verify`](/jws/verify#options) applies with the same default, plus:

| Option                   | Default               | Notes                                                             |
| ------------------------ | --------------------- | ----------------------------------------------------------------- |
| `algorithms`             | inferred from the key | Key management `alg` values to accept. Required for raw bytes.    |
| `encryptionAlgorithms`   | every supported `enc` | Content `enc` values to accept.                                   |
| `payload`                | `"json"`              | `"json"`, `"string"` or `"bytes"`. Sets the return type.          |
| `validateClaims`         | `true` under `"json"` | `false` skips the claim checks.                                   |
| `minIterations`          | `1000`                | Lowest PBES2 `p2c` accepted.                                      |
| `maxIterations`          | `600_000`             | Highest PBES2 `p2c` accepted.                                     |
| `limits.keyCandidates`   | `8`                   | Most JWK Set entries one token is tried against.                  |
| `limits.pbes2Iterations` | `2_400_000`           | PBKDF2 iterations one call may spend in total.                    |
| `returnCek`              | `false`               | Add the raw content key and the authenticated data to the result. |
| `extractable`            | `true`                | Whether the unwrapped content key may be exported.                |

## Going further

- **The producing side**: [Encrypt a payload](/jwe/encrypt).
- **Rotating keys and lookup functions**: [Use a JWK Set](/jwk/sets).
- **Tokens with several recipients**: [Encrypt for several recipients](/jwe/multi).
- **Every limit in one place**: [Limits](/safety/limits).
