tr-jwe
v2.1.1
Published
JSON Web Encryption (JWE) encrypt/decrypt for Node.js
Maintainers
Readme
tr-jwe
Compact JWE encrypt/decrypt for Node.js.
This package produces and consumes compact JWE tokens whose plaintext
is any JSON-serialisable value — object, array, string, number,
boolean, or null. It supports AES key wrap, AES-GCM key wrap, direct
encryption, RSA-based key transport, ECDH-ES, and post-quantum ML-KEM
key encapsulation.
Both a synchronous and a promise-returning asynchronous API are provided.
Reference
Installation
npm install tr-jweNode.js >=24.0.0 is required.
Exports
const { encrypt, encryptAsync, decrypt, decryptAsync, unwrap, unwrapAsync } = require('tr-jwe');encrypt(alg, jwk, data, options)
Encrypts a JSON object and returns either a compact JWE string or, when
extendedReturn is set, an object that also exposes the content-encryption
key.
alg: JWE key management algorithmjwk: recipient or wrapping key in JWK formdata: plain JavaScript objectoptions: optional object (defaults to{})
Supported options fields:
compressPayloadfalse(default): no compression.true: payload is deflated and the header carrieszip: "DEF"."auto": payload is deflated only if the result is smaller than the raw JSON; otherwise the raw JSON is encrypted and nozipheader is emitted.
extendedReturnfalse(default): the function returns the compact JWE string.true: the function returns{ token, contentEncryptionKey }wherecontentEncryptionKeyis anoctJWK suitable fordecrypt(token, contentEncryptionKey). This is useful when the caller needs to share or later re-derive the CEK without access to the wrapping key.
Unknown option keys and unexpected value types throw.
Supported alg values:
A128GCMKW,A192GCMKW,A256GCMKWA128KW,A192KW,A256KWdirRSA1_5,RSA-OAEP,RSA-OAEP-256ECDH-ES[email protected],[email protected],[email protected](see the ML-KEM section below)
Content encryption is selected automatically:
A128GCMKWandA128KWuseA128GCMA192GCMKWandA192KWuseA192GCMA256GCMKWandA256KWuseA256GCMdirpicksA128GCM,A192GCM, orA256GCMfrom key sizeECDH-ESpicksA128GCM,A192GCM, orA256GCMfrom EC curve- RSA picks
A128GCMfor 1024-bit keys andA256GCMfor 2048-bit or larger keys - ML-KEM always uses
A256GCM(the AES leg is never the weaker link for any variant)
Example:
const { encrypt, decrypt } = require('tr-jwe');
const { cipherKeyGen } = require('tr-jwk');
const key = cipherKeyGen('A256GCMKW');
const token = encrypt('A256GCMKW', key, { message: 'secret' });
const payload = decrypt(token, key);
// Compression with auto-fallback and access to the content-encryption key:
const { token: t2, contentEncryptionKey: cek } =
encrypt('A256GCMKW', key, { message: 'secret' },
{ compressPayload: 'auto', extendedReturn: true });
const samePayload = decrypt(t2, cek);decrypt(token, jwk)
Decrypts a compact JWE token and returns the parsed JSON payload.
The expected JWK depends on the token:
- AES wrap and
dir:octJWK - RSA algorithms: RSA private JWK
ECDH-ES: EC private JWK- ML-KEM:
AKPprivate JWK (seed form, as generated bytr-jwkmlKemKeyGen)
unwrap(token, jwk)
Derives or unwraps the content-encryption key from a compact JWE token and returns it as an oct JWK.
This is useful when the recipient wants the CEK itself instead of the decrypted payload.
ML-KEM key management
The algorithms [email protected], [email protected], and
[email protected] provide post-quantum key management by
direct ML-KEM (FIPS 203) key encapsulation, following
draft-ietf-jose-pqc-kem-05 in Direct Key Agreement mode.
The algorithm identifiers carry a collision-resistant suffix (RFC 7515 section 4.1.1) because the draft was not an RFC. The construction below is frozen for these identifiers: tokens minted with them will decrypt identically forever, regardless of how the standards evolve.
Standards status (July 2026): draft-ietf-jose-pqc-kem-06 removed the JOSE/JWE mechanism entirely — the document became COSE-only and moved to the COSE working group, and the JOSE working group directed JWE post-quantum algorithm registrations to an HPKE-based mechanism (draft-skokan-jose-hpke-pq-pqt) instead. Consequently, no registered unsuffixed direct-KEM JWE algorithm names are expected: the suffixed identifiers below are the stable, long-term form of this feature, implementing the direct-KEM design as last specified for JOSE in draft-05. If standards-based JOSE post-quantum interoperability is ever required, HPKE would be added as a separate algorithm family; it would not change or replace these identifiers.
Token format (compact serialization):
- The protected header carries the ML-KEM ciphertext base64url-encoded
in the
ekparameter (768, 1088, or 1568 bytes for ML-KEM-512/768/1024), and is authenticated as AAD like every tr-jwe header. - The JWE encrypted key field is empty, as in
dirandECDH-ES. encis alwaysA256GCM, which satisfies the draft's requirement of a content key at least as strong as the KEM's security category for every variant.
Content-encryption key derivation, exactly as in the draft:
CEK = KMAC256(SS, AlgorithmID || SuppPubInfo, keydatalen, "")where SS is the 32-byte ML-KEM shared secret, AlgorithmID is the
literal alg header value and SuppPubInfo is keydatalen (256) —
both encoded per RFC 7518 section 4.6.2 (32-bit big-endian length
prefix and value) — and KMAC256 is NIST SP 800-185 KMAC (via the
tr-kmac package). Note that the algorithm identifier feeds the KDF,
so suffixed and unsuffixed tokens can never be byte-interoperable;
this is inherent to the draft's design.
Encryption accepts the recipient's public (or private) AKP JWK with
alg matching the ML-KEM variant; decryption requires the private
JWK (32-byte-seed priv form). Generate keys with mlKemKeyGen from
tr-jwk (>= 2.1.0).
The draft's Key Agreement with Key Wrapping mode (ML-KEM-*+A*KW) is
not implemented: it exists for multi-recipient JWE, which the compact
serialization cannot express.
Example:
const { encrypt, decrypt } = require('tr-jwe');
const { mlKemKeyGen } = require('tr-jwk');
const { secretKey, publicKey } = mlKemKeyGen('ML-KEM-768');
const token = encrypt('[email protected]', publicKey, { message: 'secret' });
const payload = decrypt(token, secretKey);Asynchronous API
Each function has a promise-returning counterpart taking the same arguments and resolving to the same result:
encryptAsync(alg, jwk, data, options)decryptAsync(token, jwk)unwrapAsync(token, jwk)
Tokens produced by encrypt and encryptAsync are identical in
format and can be consumed interchangeably with the synchronous or
asynchronous functions. Invalid input rejects the returned promise
instead of throwing synchronously.
The asynchronous variants use the asynchronous node:crypto and
node:zlib primitives where such exist (content-encryption key
generation, random IVs, ephemeral ECDH-ES keys, ML-KEM encapsulation
and decapsulation, payload compression and decompression); the
remaining primitives (AES-GCM, RSA key transport, ECDH) have no
asynchronous counterparts in node:crypto and run in-process.
Example:
const { encryptAsync, decryptAsync } = require('tr-jwe');
const { cipherKeyGenAsync } = require('tr-jwk');
const key = await cipherKeyGenAsync('A256GCMKW');
const token = await encryptAsync('A256GCMKW', key, { message: 'secret' });
const payload = await decryptAsync(token, key);Notes
- Payload input may be any JSON-serialisable value (object, array,
string, number, boolean, or
null). - Only compact serialization is supported.
- Only AES-GCM content encryption is implemented.
- Compression uses raw DEFLATE (
zip: "DEF").
Author
Timo J. Rinne [email protected] — https://github.com/rinne/
Copyright
Copyright © 2023–2026 Timo J. Rinne [email protected].
See COPYING for the full MIT license text.
License
MIT License
