
# Encrypt a payload

> Encrypt claims, text or bytes into a compact JWE, with `alg` read from the key or the password and `enc` defaulting to `A256GCM`.

`encrypt(payload, key, options)` locks the payload so only the holder of the matching key can read it, and returns one URL-safe string of five segments. A JWE names two algorithms in its header: `alg` says how the content key reaches the recipient, `enc` says how the content is locked with it. You rarely set either: `alg` comes from the key, or from the fact that you passed a password, and `enc` defaults to `A256GCM`.

## Before you start

- Decide who opens the token. Your own server: a shared key (`generateJWK("A256KW")`) or a password. Another party: their **public** key, never yours; the matching private key stays with them. [Choose encryption algorithms](/jwe/algorithms) sorts the cases.
- Encryption hides the payload, not the header. `alg`, `enc`, `kid`, `typ` and any member you add are readable.
- A JWE made with someone's public key proves nothing about who sent it. [Sign, then encrypt](#sign-then-encrypt) when the recipient must know.
- Compression (`zip`) isn't supported and is refused.

## Encrypt for a recipient

The reporting service publishes its public key; any service can seal a record for it:

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

```ts [encrypt-for-recipient.ts]
import { encrypt } from "unjwt/jwe";
import type { JWEEncryptJWK } from "unjwt/jwe";

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

/** Seal a record so only the holder of the matching private key can read it. */
export function sealCustomer(record: CustomerRecord, recipientKey: JWEEncryptJWK) {
  return encrypt(record, recipientKey, { expiresIn: "10m" });
}
```

<!-- /automd -->

- **The recipient's public key** from `generateJWK("ECDH-ES+A256KW")`. Its `alg` becomes the header's `alg`, and its `kid` goes into the header so the recipient knows which private key to use. A private JWK here throws `ERR_JWK_INVALID`.
- **Key agreement**: for `ECDH-ES*`, `encrypt` makes a fresh ephemeral key pair per token and writes its public half into the header as `epk`. The recipient combines it with its private key to recover the content key.
- **`expiresIn: "10m"`**: the time options work as on [`sign`](/jws/sign#set-the-expiry-and-other-time-claims), and only for an object payload: with a string or bytes payload they throw `ERR_INVALID_OPTION`. A claim already in the payload is kept.

```ts
// header: { kid: "reports-2026-10", epk: { kty: "EC", crv: "P-256", x: "Geak…", y: "LWJn…" },
//           alg: "ECDH-ES+A256KW", enc: "A256GCM", typ: "JWT" }
```

## Pick the key

The key decides `alg` when you don't pass it:

| Key                                                                               | `alg` when omitted   | `enc` when omitted                     |
| --------------------------------------------------------------------------------- | -------------------- | -------------------------------------- |
| A password string                                                                 | `PBES2-HS256+A128KW` | `A256GCM`                              |
| A JWK with a key management `alg` (`A256KW`, `RSA-OAEP-256`, `ECDH-ES+A256KW`, …) | the JWK's `alg`      | the JWK's `enc` member, else `A256GCM` |
| An `oct` JWK whose `alg` is a content algorithm (`A256GCM`, `A128CBC-HS256`, …)   | `dir`                | that same algorithm                    |
| A `CryptoKey`                                                                     | none, pass `alg`     | `A256GCM`; `dir` needs `enc`           |
| Raw bytes (`Uint8Array`)                                                          | none, pass `alg`     | `A256GCM`; `dir` needs `enc`           |

```ts
await encrypt({ sub: "user_1a2b" }, await generateJWK("A256KW"));
// header: { kid: "E7Mc…", alg: "A256KW", enc: "A256GCM", typ: "JWT" }

await encrypt({ sub: "user_1a2b" }, await generateJWK("A256GCM"));
// header: { kid: "jx-E…", alg: "dir", enc: "A256GCM", typ: "JWT" }   (no encrypted key segment)

await encrypt({ sub: "user_1a2b" }, crypto.getRandomValues(new Uint8Array(32)));
// JWTError ERR_JWE_ALG_MISSING: JWE "alg" must be provided in options or inferable from the key
```

- **`dir`** uses your key as the content key itself. Generate it under the content algorithm (`generateJWK("A256GCM")`), and it infers `dir` with that `enc` and serves no other: asking it for `enc: "A128GCM"`, or using it as a wrapping key, throws `ERR_JWK_INVALID`. An `oct` JWK declared `alg: "dir"` serves any `enc` whose key length matches it, and needs `enc` passed.
- **Raw bytes** carry no role, so you name `alg`, and the matching [`decrypt`](/jwe/decrypt) names it again in `algorithms`.
- **A string** is a password and nothing else. Under any `alg` other than `PBES2-*` it throws `ERR_JWK_INVALID` rather than being used as key bytes.

## Use an AES CryptoKey

A `CryptoKey` needs `alg` and `enc` on `encrypt`. On the decrypting side, an AES-GCM `CryptoKey` admits only `A128GCMKW` / `A192GCMKW` / `A256GCMKW` (matching its length), and an AES-KW `CryptoKey` only `A*KW`. To use an AES-GCM `CryptoKey` as a `dir` content key, say so on both sides:

```ts
const key = await generateKey("A256GCM"); // an AES-GCM CryptoKey
const token = await encrypt({ sub: "user_1a2b" }, key, { alg: "dir", enc: "A256GCM" });

await decrypt(token, key);
// JWTError ERR_JWE_ALG_NOT_ALLOWED: Key management algorithm not allowed: dir
await decrypt(token, key, { algorithms: ["dir"] }); // ok
```

The same AES-GCM key could wrap content keys or be the content key, and the token's header, which anyone can write, would pick between the two. Using one key for two jobs is how keys leak, so the library takes the conservative reading and lets you opt into the other. An `oct` JWK names its role in its `alg`, so it needs no such option.

## Encrypt with a password

A string key is a password. `encrypt` derives a wrapping key from it with PBKDF2 ([RFC 7518 §4.8](https://www.rfc-editor.org/rfc/rfc7518#section-4.8)) and writes the random salt (`p2s`) and the iteration count (`p2c`) into the header:

<!-- automd:region src="../../examples/jwe/password-sealed.ts" -->

```ts [password-sealed.ts]
import { encrypt, decrypt } from "unjwt/jwe";

const ITERATIONS = 600_000;

/** Seal a backup file with a passphrase the user types. */
export function sealBackup(file: Uint8Array<ArrayBuffer>, passphrase: string) {
  return encrypt(file, passphrase, { alg: "PBES2-HS512+A256KW", p2c: ITERATIONS });
}

/** Open a backup sealed by `sealBackup`; a wrong passphrase throws `ERR_JWE_DECRYPTION_FAILED`. */
export async function openBackup(token: string, passphrase: string) {
  const { payload } = await decrypt(token, passphrase, {
    algorithms: ["PBES2-HS512+A256KW"],
    maxIterations: ITERATIONS,
    payload: "bytes",
  });
  return payload;
}
```

<!-- /automd -->

- **`p2c`** defaults to 600,000 iterations and must be between 1000 and 600,000. More iterations slow down guessing and every honest open alike; 600,000 is the most a default `decrypt` accepts, so every token `encrypt` makes opens without extra options.
- **`p2s`** is 16 random bytes per token unless you pass one of at least 8 bytes.
- **Pinning `algorithms` and `maxIterations`** on the opening side keeps a forged token from asking your server for a different, costlier derivation.
- **Bytes in, bytes out**: a `Uint8Array` payload gets no `typ` and takes no time options, and opens with `payload: "bytes"`.

Prefer a generated key whenever no person has to type the secret. [Derive keys from a password](/jwk/password) turns a password into a reusable JWK instead.

## Sign, then encrypt

A JWE made with a public key hides the claims but doesn't prove who made them. Sign the claims first, then encrypt the signed token as the payload, and mark it with `cty: "JWT"` so the recipient knows the content is itself a token ([RFC 7519 §5.2](https://www.rfc-editor.org/rfc/rfc7519#section-5.2)):

<!-- automd:region src="../../examples/jwe/nested-token.ts" -->

```ts [nested-token.ts]
import { sign, verify } from "unjwt/jws";
import type { JWSSignJWK, JWSVerifyJWK } from "unjwt/jws";
import { encrypt, decrypt } from "unjwt/jwe";
import type { JWEDecryptJWK, JWEEncryptJWK } from "unjwt/jwe";

export interface Grant {
  sub: string;
  plan: string;
}

/** Sign the claims, then encrypt the signed token: private and provably yours. */
export async function issueSealedGrant(
  grant: Grant,
  keys: { issuer: JWSSignJWK; recipient: JWEEncryptJWK },
) {
  const signed = await sign(grant, keys.issuer, { expiresIn: "1h" });
  return encrypt(signed, keys.recipient, { protectedHeader: { cty: "JWT" } });
}

/** Decrypt, then verify the token inside. */
export async function openSealedGrant(
  token: string,
  keys: { recipient: JWEDecryptJWK; issuer: JWSVerifyJWK },
) {
  const { payload: signed } = await decrypt(token, keys.recipient, { payload: "string" });
  const { payload } = await verify<Grant>(signed, keys.issuer);
  return payload;
}
```

<!-- /automd -->

The outer token's payload is a string, so it gets no `typ`, and `decrypt` needs `payload: "string"` to hand it back. The inner token's `exp` is checked by `verify`.

## Header members written for you

| `alg` family | Members `encrypt` adds                                                                            |
| ------------ | ------------------------------------------------------------------------------------------------- |
| `PBES2-*`    | `p2s` (salt), `p2c` (iteration count)                                                             |
| `A*GCMKW`    | `iv` and `tag` of the key-wrapping step                                                           |
| `ECDH-ES*`   | `epk` (ephemeral public key), `apu` and `apv` when you pass `ecdh.partyUInfo` / `ecdh.partyVInfo` |

Your `protectedHeader` can't set these, nor `alg` or `enc`. The header is built in this order, later steps winning: the key's `kid`, your `protectedHeader`, these members, then `alg` and `enc`. `typ` defaults to `"JWT"` for an object payload, `cty` is never added, and `crit` follows the rules on [`sign`](/jws/sign#add-header-members).

`apu` and `apv` name the two parties of an `ECDH-ES*` exchange and feed the key derivation, so a token made for one pair of parties doesn't open for another. Each is at most 1024 bytes; an empty one is left out.

## What you get back

A string of five base64url segments joined by dots: protected header, encrypted key, IV, ciphertext and authentication tag ([RFC 7516 §7.1](https://www.rfc-editor.org/rfc/rfc7516#section-7.1)). The encrypted key segment is empty for `dir` and bare `ECDH-ES`, which agree on the content key directly. A compact token has no room for extra authenticated data; [`encryptMulti`](/jwe/multi) takes an `aad` option.

## When it fails

| Situation                                                                                                                                                             | What happens                      |
| --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------- |
| No `alg` and the key declares none (a `CryptoKey`, raw bytes, a JWK without `alg`)                                                                                    | Throws `ERR_JWE_ALG_MISSING`.     |
| `alg: "dir"` and no `enc` from the options or the key                                                                                                                 | Throws `ERR_JWE_ENC_MISSING`.     |
| `alg` is `"none"` or unsupported, such as `RSA1_5`                                                                                                                    | Throws `ERR_JWE_ALG_NOT_ALLOWED`. |
| `enc` is unsupported                                                                                                                                                  | Throws `ERR_JWE_INVALID`.         |
| A password under a non-PBES2 `alg`, a private key, a key in the wrong role or size, an ephemeral key on another curve                                                 | Throws `ERR_JWK_INVALID`.         |
| `p2c` or `p2s` out of bounds, `apu`/`apv` too long, a `cek` or IV of the wrong length, `zip`, `epk` in the header, a bad `crit`, `typ` or `jwk`, a malformed duration | Throws `ERR_INVALID_OPTION`.      |
| A time option with a string or bytes payload                                                                                                                          | Throws `ERR_INVALID_OPTION`.      |
| Exclusive time options together, a negative `notBeforeIn`, or a `cnf.jwk` that is not a public JWK                                                                    | Throws `ERR_JWT_CLAIM_INVALID`.   |

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

## Options

| Option                                                                            | Default                    | Notes                                                                                    |
| --------------------------------------------------------------------------------- | -------------------------- | ---------------------------------------------------------------------------------------- |
| `alg`                                                                             | from the key               | How the content key reaches the recipient. Required for a `CryptoKey` or raw bytes.      |
| `enc`                                                                             | `A256GCM`                  | How the content is locked. Under `dir`, taken from the key; required when it names none. |
| `protectedHeader`                                                                 | none                       | Extra header members, such as `kid`, `typ` or `cty`.                                     |
| `expiresIn`, `expiresAt`, `notBeforeIn`, `notBeforeAt`, `issuedAt`, `currentDate` | none                       | Time claims, as on [`sign`](/jws/sign#options).                                          |
| `p2c`                                                                             | `600_000`                  | PBES2 iteration count, 1000 to 600,000.                                                  |
| `p2s`                                                                             | 16 random bytes            | PBES2 salt, at least 8 bytes.                                                            |
| `ecdh.partyUInfo`, `ecdh.partyVInfo`                                              | none                       | `ECDH-ES*` party names as bytes, at most 1024 each.                                      |
| `ecdh.ephemeralKey`                                                               | a fresh key pair per token | The sender's ephemeral key, on the recipient's curve.                                    |
| `keyManagementIV`                                                                 | random                     | IV for `A*GCMKW` key wrapping.                                                           |
| `cek`, `contentEncryptionIV`                                                      | random                     | Content key and IV, of the length `enc` needs.                                           |

Leave `cek`, `contentEncryptionIV`, `keyManagementIV` and `ecdh.ephemeralKey` unset outside test vectors: reusing an IV with the same key breaks AES-GCM.

## Going further

- **The receiving side**: [Decrypt a token](/jwe/decrypt).
- **One token for several recipients, and extra authenticated data**: [Encrypt for several recipients](/jwe/multi).
- **Which `alg` and `enc` to pick**: [Choose encryption algorithms](/jwe/algorithms).
- **Encrypted session cookies**: [Sessions](/sessions) encrypt, refresh and clear the token for you.
