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,typand 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:
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"). Itsalgbecomes the header'salg, and itskidgoes into the header so the recipient knows which private key to use. A private JWK here throwsERR_JWK_INVALID. - Key agreement: for
ECDH-ES*,encryptmakes a fresh ephemeral key pair per token and writes its public half into the header asepk. The recipient combines it with its private key to recover the content key. expiresIn: "10m": the time options work as onsign, and only for an object payload: with a string or bytes payload they throwERR_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:
| 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 |
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 keydiruses your key as the content key itself. Generate it under the content algorithm (generateJWK("A256GCM")), and it infersdirwith thatencand serves no other: asking it forenc: "A128GCM", or using it as a wrapping key, throwsERR_JWK_INVALID. AnoctJWK declaredalg: "dir"serves anyencwhose key length matches it, and needsencpassed.- Raw bytes carry no role, so you name
alg, and the matchingdecryptnames it again inalgorithms. - A string is a password and nothing else. Under any
algother thanPBES2-*it throwsERR_JWK_INVALIDrather 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"] }); // okThe 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:
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;
}p2cdefaults 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 defaultdecryptaccepts, so every tokenencryptmakes opens without extra options.p2sis 16 random bytes per token unless you pass one of at least 8 bytes.- Pinning
algorithmsandmaxIterationson the opening side keeps a forged token from asking your server for a different, costlier derivation. - Bytes in, bytes out: a
Uint8Arraypayload gets notypand takes no time options, and opens withpayload: "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):
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 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.
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
| 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 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. |
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.
- One token for several recipients, and extra authenticated data: Encrypt for several recipients.
- Which
algandencto pick: Choose encryption algorithms. - Encrypted session cookies: Sessions encrypt, refresh and clear the token for you.