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). 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.
  • 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:

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

KeyWhen to use it
A private JWKOne recipient, one key pair (RSA-OAEP*, ECDH-ES*).
An oct JWKA shared key (A*KW, A*GCMKW) or a dir content key.
A password stringPBES2 tokens only; any other alg is refused.
A CryptoKey or raw bytesKeys you already hold in that form. Bytes declare no algorithm: pass algorithms.
A JWK Set ({ keys: [...] })Rotation, several keys. See Use a JWK Set.
A lookup function ({ header, token }) => keyKeys 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: 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 explains why.

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:

OptionDefaultWhat it bounds
minIterations1000Lowest p2c accepted (RFC 7518 §4.8.1.2).
maxIterations600_000Highest p2c one attempt may ask for. Raise it only for a sender that mints more.
limits.pbes2Iterations2_400_000Total 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 does.

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: audience, issuer, subject, maxTokenAge, requiredClaims, clockTolerance, currentDate, typ, recognizedHeaders, validateClaims. Validate 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:

payloadYou getClaims checked
omitted or "json"the claims object, typed decrypt<MyClaims>()yes
"string"the plaintext as UTF-8 textno
"bytes"the plaintext as a Uint8Arrayno
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 holds a string, so it opens with payload: "string".

#What you get back

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:

SituationWhat happens
An option is empty or malformedThrows ERR_INVALID_OPTION, before the token is read.
A claim option with a non-JSON payload or with validateClaims: falseThrows ERR_INVALID_OPTION, before the token is read.
Not a string, not five segments, or a header without alg and encThrows ERR_JWE_INVALID.
alg is "none" or unsupportedThrows ERR_JWE_ALG_NOT_ALLOWED.
enc is unsupported, or the header carries zipThrows ERR_JWE_INVALID.
enc is not in encryptionAlgorithmsThrows ERR_JWE_ALG_NOT_ALLOWED.
crit names an extension you didn't list, typ doesn't match, or a segment is malformedThrows ERR_JWE_INVALID.
The lookup function returned undefinedThrows ERR_JWK_KEY_NOT_FOUND.
The lookup function threw an error that is not a JWTErrorThrows ERR_JWK_KEY_NOT_FOUND, with that error as cause.
The lookup function threw a JWTErrorThrows that error.
alg is not in algorithms, or nothing can be inferred from the keyThrows ERR_JWE_ALG_NOT_ALLOWED.
The JWK Set has no entry for the kid, or more candidates than limits.keyCandidatesThrows ERR_JWK_KEY_NOT_FOUND.
A PBES2 count outside the bounds or past the budgetThrows ERR_JWE_INVALID.
No key, a public key, a password under a non-PBES2 alg, or a key in the wrong roleThrows ERR_JWK_INVALID.
Wrong key, wrong password, or a changed tokenThrows ERR_JWE_DECRYPTION_FAILED.
The plaintext doesn't fit the payload modeThrows ERR_JWE_INVALID.
A claim check failsThrows ERR_JWT_CLAIM_MISSING, ERR_JWT_CLAIM_INVALID, ERR_JWT_NBF or ERR_JWT_EXPIRED, as on verify.

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

#Options

Every claim option of verify applies with the same default, plus:

OptionDefaultNotes
algorithmsinferred from the keyKey management alg values to accept. Required for raw bytes.
encryptionAlgorithmsevery supported encContent enc values to accept.
payload"json""json", "string" or "bytes". Sets the return type.
validateClaimstrue under "json"false skips the claim checks.
minIterations1000Lowest PBES2 p2c accepted.
maxIterations600_000Highest PBES2 p2c accepted.
limits.keyCandidates8Most JWK Set entries one token is tried against.
limits.pbes2Iterations2_400_000PBKDF2 iterations one call may spend in total.
returnCekfalseAdd the raw content key and the authenticated data to the result.
extractabletrueWhether the unwrapped content key may be exported.

#Going further