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 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 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:

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" });
}
  • 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, 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.
// 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:

Keyalg when omittedenc when omitted
A password stringPBES2-HS256+A128KWA256GCM
A JWK with a key management alg (A256KW, RSA-OAEP-256, ECDH-ES+A256KW, …)the JWK's algthe JWK's enc member, else A256GCM
An oct JWK whose alg is a content algorithm (A256GCM, A128CBC-HS256, …)dirthat same algorithm
A CryptoKeynone, pass algA256GCM; dir needs enc
Raw bytes (Uint8Array)none, pass algA256GCM; dir needs enc
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 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:

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) and writes the random salt (p2s) and the iteration count (p2c) into the header:

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;
}
  • 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 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):

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;
}

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 familyMembers encrypt adds
PBES2-*p2s (salt), p2c (iteration count)
A*GCMKWiv 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.

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). 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 takes an aad option.

#When it fails

SituationWhat 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 keyThrows ERR_JWE_ENC_MISSING.
alg is "none" or unsupported, such as RSA1_5Throws ERR_JWE_ALG_NOT_ALLOWED.
enc is unsupportedThrows 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 curveThrows 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 durationThrows ERR_INVALID_OPTION.
A time option with a string or bytes payloadThrows ERR_INVALID_OPTION.
Exclusive time options together, a negative notBeforeIn, or a cnf.jwk that is not a public JWKThrows ERR_JWT_CLAIM_INVALID.

Handle errors lists every code and what to do about it.

#Options

OptionDefaultNotes
algfrom the keyHow the content key reaches the recipient. Required for a CryptoKey or raw bytes.
encA256GCMHow the content is locked. Under dir, taken from the key; required when it names none.
protectedHeadernoneExtra header members, such as kid, typ or cty.
expiresIn, expiresAt, notBeforeIn, notBeforeAt, issuedAt, currentDatenoneTime claims, as on sign.
p2c600_000PBES2 iteration count, 1000 to 600,000.
p2s16 random bytesPBES2 salt, at least 8 bytes.
ecdh.partyUInfo, ecdh.partyVInfononeECDH-ES* party names as bytes, at most 1024 each.
ecdh.ephemeralKeya fresh key pair per tokenThe sender's ephemeral key, on the recipient's curve.
keyManagementIVrandomIV for A*GCMKW key wrapping.
cek, contentEncryptionIVrandomContent 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