Repository navigation
Conversation
…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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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_idheader 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:
HPKE-0…HPKE-7enc, one recipient, encrypted key = encapsulated key, empty IV and tagHPKE-0-KE,-1-KE,-2-KE,-3-KE,-5-KE,-7-KEencas usual, encapsulated key inek, combinable with other recipientsSuites: P-256/384/521 (
EC), X25519/X448 (OKP), HKDF-SHA256/384/512, AES-128/256-GCM, ChaCha20Poly1305 (HPKE-4,HPKE-6). Revision -22 removedHPKE-4-KEandHPKE-6-KE.The issue was written against an earlier revision. In -22, Integrated Encryption carries the encapsulated key in
encrypted_key(noek), uses an empty HPKEinfoand the RFC 7516 AAD as HPKEaad. Key Encryption uses theRecipient_structure("JOSE-HPKE rcpt" || 0xFF || enc || 0xFF || extra) asinfo, which binds the CEK toenc. This PR follows -22.Design
HPKE core: in the library,
@internalAlgorithm\KeyEncryption\Util\HPKE\{HKDF, AEAD, DHKEM, CipherSuite}hold only what the draft needs: the single-shot API inmode_baseandmode_psk, no export interface, no Auth modes (draft-ietf-hpke-hpke removed them). DH and AEAD run on OpenSSL (X25519 on sodium when loaded, asOKPKeydoes). The ephemeral key isDeriveKeyPair(random(Nsk))as §7.1.3 definesGenerateKeyPair, 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 pullsext-gmp,sodium_compat,easy-ecc,eccandpqcrypto_compat, and still lacks P-384 and X448. Because the classes are@internal, they can move to a sharedspomky-labs/hpkelater (cose-lib has no COSE-HPKE either) without a BC concern.Key Encryption: no change to the builder or the decrypter
AbstractHPKEKEimplementsKeyAgreementWithKeyWrappingand returnsMODE_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 ofmode_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
IntegratedEncryptioninterface (MODE_INTEGRATED), withencryptPayload()/decryptPayload()and anEncryptedPayloadvalue object (encrypted key + ciphertext). No output parameter, in line with the 5.0 direction (WrappedKey,EncryptedContent).JWEBuilder::build()andJWEDecryptertake a separate branch only whenalgnames such an algorithm. The existing path is untouched, including its error order. The branch enforces the generic rules of the mode: one recipient, noenc,algin the protected header, empty IV and tag, encrypted key present. Structural violations throw, as missingenc/algdo today. Algorithm-specific checks (ekpresent) are per-key failures, asepkis for ECDH-ES.Pre-shared key
oct, at least 32 bytes (§5.1.2).psk_idis set by the application, askidis, and holds the base64url encoding of the identifier. If the JWK has akid, it must match.mode_basetoken, so such a token is not decrypted when a PSK is given.JWELoadertakes 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)
JSONFlattenedSerializerandJSONGeneralSerializeralways wroteivandtagand required them. They now omit them when empty and accept their absence. A JSON JWE without them used to end in a rawTypeError(not even anInvalidSerializationException), 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.phpregisters each alias only whenisSupported()(X25519: sodium or OpenSSL on PHP 8.4; X448: PHP 8.4; ChaCha20Poly1305: an OpenSSL providing it). Otherwise the constructors throwMissingDependencyException.Acceptance criteria of #729
scripts/jwe.jsin 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.HPKE-0-KE+HPKE-3-KE+RSA-OAEP-256), and throughJWELoader+AlgorithmChecker. The ChaCha20 suites are gated.algsubstituted within the same KEM (HPKE-0→7, HPKE-3→4, HPKE-0-KE→7-KE),ekreplaced, AAD or protected header changed,encchanged (Recipient_structure binding),infomismatch.HPKE-*withencis rejected (builder and decrypter);HPKE-*-KEwithoutencis rejected (builder and decrypter).feat/hpke-jweof web-token/jwt-doc — a dedicated HPKE page, the algorithm tables and the 4.2 → 4.3 migration guide (mkdocs build --strictpasses); 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 twoTypeErrors, are the pre-existing serializer bug above.Green.
phpunit-11,ghcr.io/spomky-labs/phpqa:8.2, freshcomposer installMutation check. Eight hand-made mutations of the security invariants were each caught: JWE AAD ignored;
encdropped from the Recipient_structure; PSK downgrade accepted;enc, IV/tag or a second recipient accepted in integrated mode; mode byte fixed to base; PSKkidnot checked.QA
Warning
The analysis gates are red on
4.3.xitself since 2026-10-22 (run 39832847019), from tool drift in thephpqaimages: ECS no longer hasSetList::SYMPLIFY, Rector wants changes in 24 files, PHPStan reports an unmatched baseline entry onExperimental\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.SYMPLIFY: clean.JSONFlattenedSerializer) is flagged for its pre-existing$recipientIndex ??= 0.Backward compatibility
src/on 4.3.x (13a86f2e) vs this branch. Additions only, nothing removed or changed.iv/tagnow unserializes, where it used to throw aTypeErrorafter a PHP warning.Not in this PR
HPKEKeyAnalyzerchecking thealg/kty/crvtable of §9. The algorithms already refuse a key of the wrong type or curve.