Skip to content

feat(encryption): HPKE for JWE — Integrated Encryption and Key Encryption (draft-ietf-jose-hpke-encrypt) - #740

Draft
Spomky wants to merge 4 commits into
4.3.xfrom
feat/hpke-jwe
Draft

Spomky wants to merge 4 commits into
4.3.xfrom
feat/hpke-jwe

Conversation

@Spomky

@Spomky Spomky commented Oct 30, 2026 •

Copy link
Copy Markdown
Member

Closes #729

Note

Opened as a draft because #729 says the implementation is not to be merged before the RFC number exists. Where things stand on 2026-10-30: draft-ietf-jose-hpke-encrypt-22 is in the RFC Editor queue, blocked on its normative reference draft-ietf-hpke-hpke, and IANA registered the fourteen identifiers and the ek / psk_id header parameters on 2026-09-29, so AUTH48 is no longer likely to change them. Whether that is enough for 4.3.0 is your call.

What

draft-ietf-jose-hpke-encrypt-22 brings HPKE (RFC 9180, revised by draft-ietf-hpke-hpke-03) to JWE, in two key management modes:

Mode Identifiers What HPKE encrypts Token
Integrated Encryption (new mode) HPKE-0 … HPKE-7 the payload no enc, one recipient, encrypted key = encapsulated key, empty IV and tag
Key Encryption HPKE-0-KE, -1-KE, -2-KE, -3-KE, -5-KE, -7-KE the CEK enc as usual, encapsulated key in ek, combinable with other recipients

Suites: P-256/384/521 (EC), X25519/X448 (OKP), HKDF-SHA256/384/512, AES-128/256-GCM, ChaCha20Poly1305 (HPKE-4, HPKE-6). Revision -22 removed HPKE-4-KE and HPKE-6-KE.

The issue was written against an earlier revision. In -22, Integrated Encryption carries the encapsulated key in encrypted_key (no ek), uses an empty HPKE info and the RFC 7516 AAD as HPKE aad. Key Encryption uses the Recipient_structure ("JOSE-HPKE rcpt" || 0xFF || enc || 0xFF || extra) as info, which binds the CEK to enc. This PR follows -22.

Design

HPKE core: in the library, @internal

Algorithm\KeyEncryption\Util\HPKE\{HKDF, AEAD, DHKEM, CipherSuite} hold only what the draft needs: the single-shot API in mode_base and mode_psk, no export interface, no Auth modes (draft-ietf-hpke-hpke removed them). DH and AEAD run on OpenSSL (X25519 on sodium when loaded, as OKPKey does). The ephemeral key is DeriveKeyPair(random(Nsk)) as §7.1.3 defines GenerateKeyPair, with a constant-time comparison against the curve order. This makes encapsulation reproducible from the RFC 9180 vectors.

I did not use paragonie/hpke: v0.8, pre-1.0, it pulls ext-gmp, sodium_compat, easy-ecc, ecc and pqcrypto_compat, and still lacks P-384 and X448. Because the classes are @internal, they can move to a shared spomky-labs/hpke later (cose-lib has no COSE-HPKE either) without a BC concern.

Key Encryption: no change to the builder or the decrypter

AbstractHPKEKE implements KeyAgreementWithKeyWrapping and returns MODE_ENCRYPT. With a DH-based KEM, HPKE is mechanically a key agreement followed by an AEAD wrap. More to the point, that interface is the one that hands the sender key over, and the sender key is the pre-shared key of mode_psk. The alternative, KeyEncryption, would have meant passing the sender key as an undeclared extra argument to every implementation.

Integrated Encryption: new interface and a dedicated branch

  • New IntegratedEncryption interface (MODE_INTEGRATED), with encryptPayload() / decryptPayload() and an EncryptedPayload value object (encrypted key + ciphertext). No output parameter, in line with the 5.0 direction (WrappedKey, EncryptedContent).
  • JWEBuilder::build() and JWEDecrypter take a separate branch only when alg names such an algorithm. The existing path is untouched, including its error order. The branch enforces the generic rules of the mode: one recipient, no enc, alg in the protected header, empty IV and tag, encrypted key present. Structural violations throw, as missing enc/alg do today. Algorithm-specific checks (ek present) are per-key failures, as epk is for ECDH-ES.

Pre-shared key

  • The PSK is the sender key: oct, at least 32 bytes (§5.1.2).
  • psk_id is set by the application, as kid is, and holds the base64url encoding of the identifier. If the JWK has a kid, it must match.
  • Downgrade protection: a PSK given to the decrypter is never ignored. Anyone holding the recipient's public key can produce a mode_base token, so such a token is not decrypted when a PSK is given.
  • Same limitation as ECDH-SS: JWELoader takes no sender key.

Application information

Optional constructor argument: new HPKE3($info) / new HPKE0KE($recipientExtraInfo), empty by default. The bundle registers the default instances.

JSON serializers (RFC 7516 §7.2.1)

JSONFlattenedSerializer and JSONGeneralSerializer always wrote iv and tag and required them. They now omit them when empty and accept their absence. A JSON JWE without them used to end in a raw TypeError (not even an InvalidSerializationException), which the integrated JSON vectors of the draft hit. Existing tokens serialize byte for byte as before: no existing algorithm has an empty IV or tag.

Bundle

encryption_hpke.php registers each alias only when isSupported() (X25519: sodium or OpenSSL on PHP 8.4; X448: PHP 8.4; ChaCha20Poly1305: an OpenSSL providing it). Otherwise the constructors throw MissingDependencyException.

Acceptance criteria of #729

  • The draft's appendix A vectors decrypt, compact and JSON, for the 14 identifiers. Re-encrypting with the vector's ephemeral material is not possible: the CEK, IV and ephemeral keys of those vectors were random and are not published (see scripts/jwe.js in the WG repo). Instead, new tokens are built for the vector keys, and the HPKE core replays the deterministic RFC 9180 vectors (ikmE → enc, shared secret, key schedule, ciphertext) for the 7 suites that file covers, in both modes. P-384/SHA-384 is not in that file; it is covered by the JOSE vectors.
  • Round trips for the 8 integrated and 6 key-encryption identifiers with generated keys: compact, flattened (with AAD), general, multi-recipient (HPKE-0-KE + HPKE-3-KE + RSA-OAEP-256), and through JWELoader + AlgorithmChecker. The ChaCha20 suites are gated.
  • Tampering fails: alg substituted within the same KEM (HPKE-0→7, HPKE-3→4, HPKE-0-KE→7-KE), ek replaced, AAD or protected header changed, enc changed (Recipient_structure binding), info mismatch.
  • HPKE-* with enc is rejected (builder and decrypter); HPKE-*-KE without enc is rejected (builder and decrypter).
  • Bundle registration of the 14 aliases.
  • Docs: branch feat/hpke-jwe of web-token/jwt-doc — a dedicated HPKE page, the algorithm tables and the 4.2 → 4.3 migration guide (mkdocs build --strict passes); its PR is not opened yet. The changelog comes from the release notes of the 4.3.0 milestone.

Tests

Red first. Run against unmodified 4.3.x: 314 tests, 306 errors (missing classes) and 4 failures. Two of those failures, plus two TypeErrors, are the pre-existing serializer bug above.

Green.

Platform Result
PHP 8.5, PHPUnit 13 (local) 1711 tests OK. 335 new, 4 skipped and 2 incomplete, all pre-existing
PHP 8.2, phpunit-11, ghcr.io/spomky-labs/phpqa:8.2, fresh composer install 1711 tests OK. The only HPKE skips are the X448 suites, which need PHP 8.4

Mutation check. Eight hand-made mutations of the security invariants were each caught: JWE AAD ignored; enc dropped from the Recipient_structure; PSK downgrade accepted; enc, IV/tag or a second recipient accepted in integrated mode; mode byte fixed to base; PSK kid not checked.

QA

Warning

The analysis gates are red on 4.3.x itself since 2026-10-22 (run 39832847019), from tool drift in the phpqa images: ECS no longer has SetList::SYMPLIFY, Rector wants changes in 24 files, PHPStan reports an unmatched baseline entry on Experimental\KeyEncryption\Chacha20Poly1305. The test jobs depend on these gates and are skipped for every PR. That is why the tests above were run locally. Repairing the gates belongs in a separate PR.

  • PHPStan (phpqa:8.4, caches cleared): no new error and no new baseline entry. Only the pre-existing Chacha20Poly1305 line remains.
  • ECS: run on the 34 changed files with the CI config minus SYMPLIFY: clean.
  • Rector: the same 24 files as on the base. The one shared file (JSONFlattenedSerializer) is flagged for its pre-existing $recipientIndex ??= 0.
  • Deptrac: 0 violations. parallel-lint: OK.

Backward compatibility

  • Signature pass: reflection dump of src/ on 4.3.x (13a86f2e) vs this branch. Additions only, nothing removed or changed.
  • Behavioural pass: the same probe run on both trees (serializations, unserializations, round trips for dir / A128KW / RSA-OAEP-256 / ECDH-ES / ECDH-ES+A128KW / ECDH-SS / PBES2, builder and decrypter errors, deprecation counts). Identical, except the intended change: a JSON JWE without iv/tag now unserializes, where it used to throw a TypeError after a PHP warning.

Not in this PR

…ion (draft-ietf-jose-hpke-encrypt)

draft-ietf-jose-hpke-encrypt-22 brings HPKE (RFC 9180, revised by
draft-ietf-hpke-hpke) to JWE: "HPKE-0" to "HPKE-7" use a new key
management mode, Integrated Encryption, where HPKE encrypts the
payload itself, and the six "HPKE-*-KE" encrypt the CEK. The draft is
in the RFC Editor queue, and IANA registered the fourteen identifiers
and the "ek" and "psk_id" header parameters on 2026-09-29. The
library had nothing HPKE-related.

HPKE is carried by four internal classes under KeyEncryption\Util\HPKE,
limited to what the draft needs: the single-shot API in mode_base and
mode_psk, DHKEM over P-256, P-384, P-521, X25519 and X448,
HKDF-SHA256/384/512, AES-128/256-GCM and ChaCha20Poly1305. The DH and
the AEADs are OpenSSL's, X25519 is sodium's when it is loaded. The
ephemeral key is DeriveKeyPair(random(Nsk)), which makes the
encapsulation reproducible from the RFC 9180 test vectors.
paragonie/hpke was not used: it is pre-1.0, pulls gmp, sodium_compat,
two ECC libraries and pqcrypto_compat, and lacks P-384 and X448.

Key Encryption implements KeyAgreementWithKeyWrapping with the Key
Encryption mode: that interface hands the sender key over, and the
sender key is the pre-shared key of mode_psk, so neither the builder
nor the decrypter changes for it. The algorithm adds "ek"; the HPKE
info is the Recipient_structure, which binds the CEK to "enc".

Integrated Encryption is a new IntegratedEncryption interface and a
dedicated branch of JWEBuilder::build() and of the decrypter, taken
only when "alg" designates such an algorithm: a single recipient whose
encrypted key is the encapsulated key, no "enc", "alg" in the
protected header, empty IV and tag, the RFC 7516 additional
authenticated data as HPKE aad.

The pre-shared key is the sender key (oct, at least 32 bytes) and
"psk_id", the base64url of its identifier, is set by the application,
as "kid" is; a "kid" on the key must match it. A pre-shared key given
to the decrypter is never ignored: a mode_base token, which anyone
holding the public key can produce, is not decrypted where the sender
is expected to be authenticated.

The JWE JSON serializers always wrote "iv" and "tag" and required
them: they now leave them out when empty and accept their absence
(RFC 7516 section 7.2.1). A JSON token without them used to end in a
TypeError, which the integrated vectors of the draft hit.

The bundle registers each alias when the platform can run it: X25519
needs sodium or OpenSSL on PHP 8.4, X448 PHP 8.4, ChaCha20Poly1305 an
OpenSSL providing it. isSupported() tells, and the constructors throw
a MissingDependencyException otherwise.

The tests decrypt the fourteen vectors of the draft (appendix A,
compact and JSON) and build new tokens for their keys, replay the
RFC 9180 vectors of the seven suites the file covers (P-384 is not in
it) in both modes, and check the round trips, the multi-recipient
JWEs, the loader, the pre-shared key, the binding of "alg", "ek",
"enc", the AAD and the info, and the rejection of malformed integrated
tokens. Eight mutations of these invariants were each caught.

Backward compatibility was verified: the reflection dump of the public
API only shows additions, and the behavioural probes run against
4.3.x are identical (serializations byte for byte, round trips,
exceptions, deprecations), except that a JSON JWE without "iv" or
"tag" now unserializes instead of throwing a TypeError. Verified on
PHP 8.2 (PHPUnit 11) and 8.5.

Closes #729
* origin/4.3.x: (98 commits)
  fix(encryption): deprecate deriving the passwords of a key set beyond the PBES2 cap
  fix(encryption): check the size of an AES-GCM wrapped key before unwrapping it
  ci: add to the PHPStan baseline the four errors reported on 4.3.x whatever the change
  ci(github): use a closing keyword in the pull request template
  fix(bundle): keep the service ids of the library "none" and "RSA1_5" classes, deprecated
  fix(key-management): JKUFactory and X5UFactory extend UrlKeySetFactory again
  fix(composer): require web-token/jwt-library ^4.3 in the bundle and experimental packages
  fix(json): bound the JSON documents decoded outside of a token
  fix(serializers): chain the reason of the serializer a token belongs to
  fix(serializers): chain the bound a token goes beyond in the serializer managers
  fix(serializers): name the bound a token goes beyond when it is decoded
  fix(sd-jwt): refuse the unparsable unprotected headers as the other claims
  fix(sd-jwt): name the bound a Disclosure factory hits
  fix(sd-jwt): tell the decoding bounds apart from invalid JSON
  fix(console): inject the key factory into the generator commands through a setter
  Remove the Scorecards workflow
  test(sd-jwt): keep the anonymous JsonSerializable valid on PHP 8.2
  fix(sd-jwt): create only the Disclosures that can be parsed
  fix(sd-jwt): refuse at issuance the SD-JWTs the Holder and the Verifier reject
  fix(sd-jwt): serialize the objects of the Disclosures as the payload
  ...

# Conflicts:
#	src/Library/Encryption/JWEDecrypter.php
…ing it

PHPStan 2.3.7 narrows the return value of getIV() and getTag() after the
emptiness check, so it reports the '?? ""' of the second call as applied to
an expression that is never null. The two serializers now read each value
once. Nothing changes when the code runs.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(encryption): HPKE for JWE (draft-ietf-jose-hpke-encrypt, awaiting AD go-ahead)

1 participant