Repository navigation
feat(key management): direct, AES-KW, HKDF, ECDH-ES/SS recipient algorithms (RFC 9053 §5–6) (#201) - #213
Merged
Conversation
…hms (RFC 9053 §5–6) Cose\Algorithm\KeyManagement: the three families of RFC 9052 §8.5 behind KeyManagement (recoverKey / protectKey against a RecipientLayer): DirectEncryption (direct, direct+HKDF-SHA-256/512, direct+HKDF-AES-128/256), KeyWrap (A128KW, A192KW, A256KW over spomky-labs/aes-key-wrap) and KeyAgreement (ECDH-ES/SS + HKDF-256/512, ECDH-ES/SS + A128/192/256KW). Hkdf is the RFC 5869 construction with an injectable PRF, HMAC or the untruncated AES-CBC-MAC of RFC 9053 §5.1 (extract skipped). KdfContext builds COSE_KDF_Context exactly as §5.2 spells it. EllipticCurveDiffieHellman validates an EC2 point before any scalar multiplication and refuses an all-zero OKP secret (RFC 7748 §6.1). CoseHeaders gains the labels and typed accessors of the ECDH and HKDF parameters (-1, -2, -3, -20 to -26) and of the RFC 9360 §3 *-sender ones. Ec2Key gains isOnCurve() / assertOnCurve(). EncryptStructure::encryptFor() encrypts for N recipients; a direct recipient refuses siblings.
…y management algorithms The harness walks the COSE_recipient list the way a receiver does, nested levels included, hands each entry to the algorithm its headers announce, and checks every intermediate the generator recorded: COSE_KDF_Context, ECDH shared secret, KEK, CEK. Where the sending side is deterministic (AES-KW, direct+HKDF, ECDH-SS) the recipient is produced again and has to match byte for byte. The 194 key-management skips become runs; only the three RSAES-OAEP fixtures stay skipped.
…ayer, and every algorithm family RFC 5869 and RFC 3394 vectors, the cose-wg intermediates per algorithm, a point on the quadratic twist of P-256 refused before any scalar multiplication, the all-zero X25519/X448 secret, the key restrictions of RFC 9053 §6, the recipient shape rules of RFC 9052 §8.5, the typed header accessors, and EncryptStructure::encryptFor() end to end.
…ple 05 with the real thing README and doc/Usage.md gain a Key Management Algorithms section with the eighteen identifiers, the two sides of every algorithm, what each family enforces, the static-static parameters and the KDF context; the header parameter table lists -1 to -3, -20 to -29. RELEASES.md describes the feature and the new spomky-labs/aes-key-wrap dependency. Example 05 no longer hand-rolls AES Key Wrap: encryptFor() for three recipients of three families, a direct recipient, and the layering of RFC 9052 Appendix B.
This was referenced Sep 12, 2026
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.
Target branch: 4.9.x
Resolves issue #201 (Closes #201)
Part of #202
What
The content key distribution methods of RFC 9053 §5–6: the eighteen identifiers of the issue, in a new namespace
Cose\Algorithm\KeyManagement, with theCOSE_KDF_Contextof §5.2 built exactly, the HKDF of §5.1 with an injectable PRF, ECDH on every curve the RFC names, and the recipient rules of RFC 9052 §8.5 enforced on both sides. Everything is additive: new classes, new methods, new constants, no existing public signature changes.The families
One interface per class of RFC 9052 §8.5, all under
KeyManagement, whose two methods are the two sides of every algorithm —recoverKey(RecipientLayer, Key): string(receiving) andprotectKey(RecipientLayer, Key, ?string): ProtectedKey(sending) — plusisDirect().DirectEncryptionDirect(-6),DirectHKDF_SHA256(-10),DirectHKDF_SHA512(-11),DirectHKDF_AES128(-12),DirectHKDF_AES256(-13)KeyWrap(wrap(),unwrap(),keyLength())A128KW(-3),A192KW(-4),A256KW(-5) over spomky-labs/aes-key-wrapKeyAgreement(isEphemeralStatic(),keyWrap(),agree())ECDH_ES_HKDF256(-25),ECDH_ES_HKDF512(-26),ECDH_SS_HKDF256(-27),ECDH_SS_HKDF512(-28),ECDH_ES_A128KW(-29),ECDH_ES_A192KW(-30),ECDH_ES_A256KW(-31),ECDH_SS_A128KW(-32),ECDH_SS_A192KW(-33),ECDH_SS_A256KW(-34)RecipientLayeris what an algorithm runs against: the headers and ciphertext of theCOSE_recipient, the algorithm and key length of the key it protects (the content algorithm, or the key wrap of the recipient above for a nested one —keyLengthOf()infers it from an AEAD, a MAC or a key wrap), whether the recipient is alone at its level, and what the application adds: the sender's static key (withSenderKey()), the party information its protocol implies (withPartyU()/withPartyV(), completing the headers element by element),SuppPubInfo.otherandSuppPrivInfo.ProtectedKeyis what the sending side returns: the key of the layer below, the header parameters to merge into the unprotected bucket (theephemeral key), the recipient ciphertext.What the issue asked, point by point
protectedMUST be zero-length (either empty form of §3 accepted, as for every recipient),ciphertextMUST be a zero-lengthbstr(nil refused too),recipientsMUST be absent, only recipient of the message. Key type MUST be Symmetric (§6.1.1). Noalg/key_opsenforcement: the key is the content key, the content algorithm checks it.spomky-labs/aes-key-wrap^7.0added torequire(it needsext-mbstring; deptrac knows theAESKW\layer). The protected bucket MUST be empty (§6.2.1). KEK length checked against the identifier; key to wrap a multiple of 64 bits, ≥ 128; a failed integrity check is one message,AesKeyWrap::UNWRAP_FAILED, for a wrong KEK, a tampered, truncated or unaligned value alike.Hkdfis one implementation of the RFC 5869 construction with the PRF as a parameter:Hkdf::hmac('sha256'|'sha512')extracts and expands;Hkdf::aesCbcMac(128|256)uses the untruncatedAESMAC128_128/AESMAC256_128of feat(mac): AES-CBC-MAC algorithms 14, 15, 25, 26 (RFC 9053 §3.2) #200 as PRF, skips the extract step, ignores the salt, and requires the secret to be exactly the AES key length.hash_hkdf()is not used but the HMAC form is checked against it and against RFC 5869 A.1–A.3. NoECDH + HKDF-AESexists.COSE_KDF_Context(§5.2) —KdfContext+PartyInfo:[AlgorithmID, [id, nonce, other], [id, nonce, other], [keyDataLength, protected, ? other], ? SuppPrivInfo]; absent party fields arenil, never omitted;nonceisbstr / int;keyDataLengthin bits;protectedas carried orh''when empty (emptyOrSerializedMap());other/SuppPrivInfoonly when the application defines them. EveryContext_hexof the fixtures matches byte for byte,hmac-sha-256-13/14(pub other, priv info) andRFC8152/Appendix_C_3_2(identities known from the protocol, not sent) included.EllipticCurveDiffieHellman:openssl_pkey_derive()on the PEM forms for P-256/384/521, X25519, X448 and the Brainpool curves where the build has them (isCurveSupported(), the feat(algorithms): finish RFC 9864 — Brainpool availability gate, per-identifier tests, cross-verification, IANA deprecation note #194 gate); secp256k1 and the Edwards curves refused with a message. Point validation is explicit and runs first:Ec2Key::isOnCurve()/assertOnCurve()(new, the constructor unchanged) checky² = x³ + ax + bandx, y < pbefore OpenSSL sees the point. An all-zero OKP secret is refused (RFC 7748 §6.1). Key types and curves must match.generateEphemeralKey()draws a fresh pair on the recipient's curve,kty/crv/x/y/dand nothing else.{1, -1, -2, -3}and comes in throughCoseHeaders::getEphemeralKey(), which refuses a private part and a non-EC2/OKP type; a compressedydecompresses through feat(keys): COSE Key Thumbprint (RFC 9679) and compressed EC2 points #197.withSenderKey(), private when sending, public when receiving, resolved fromstatic key idor the*-senderparameters after the validation the application owns); astatic key(-2) carried in the headers is used only when nothing was supplied. The sending side refuses to run without asaltor aPartyU nonce(§6.3.1); the receiving side derives with what the message carries —p256-ss-wrap-*of cose-wg carry neither.key_opsMUST be empty on the public key of the agreement, MUST includederive key/derive bitson the private one; enforced by default like the content encryption algorithms (feat(encryption): AEAD content encryption algorithms — AES-GCM, AES-CCM, ChaCha20/Poly1305 (RFC 9053 §4) #199),withKeyRestrictionsEnforced(false)lifts it.CoseHeaders::LABEL_EPHEMERAL_KEY(-1),LABEL_STATIC_KEY(-2),LABEL_STATIC_KEY_ID(-3),LABEL_SALT(-20),LABEL_PARTY_U_IDENTITY/NONCE/OTHER(-21/-22/-23),LABEL_PARTY_V_*(-24/-25/-26), withgetEphemeralKey(),getStaticKey(),getStaticKeyId(),getSalt(),getPartyUIdentity()… — and the three accessors feat(headers): X.509 header parameters x5bag, x5chain, x5t, x5u (RFC 9360) #196 deferred to here:getX5TSender(),getX5USender(),getX5ChainSender().EncryptStructure::encryptFor(ContentEncryption, string $plaintext, string $nonce, iterable<Recipient>, ?MapObject $unprotected): CoseEncryptTag— draws the CEK, runs each recipient's algorithm, fills theCOSE_recipientarray, adds theIVunless anIVorPartial IVis already there.Cose\Encryption\Recipientis the input (algorithm, key, headers; thealgis added where the family allows it: unprotected fordirectand AES-KW, protected otherwise). A direct algorithm —direct,direct+HKDF-*, and alsoECDH-*+HKDF-*, RFC 9052 §8.5.4 says the same of direct key agreement — refuses to coexist with another recipient.examples/05-encrypt-recipients.phprewritten:encryptFor()for A256KW, ECDH-ES + A128KW (P-256) and ECDH-SS + A128KW (X25519) with each recipient opening the message, a direct recipient and the refused sibling, and the layering of RFC 9052 Appendix B by hand.One design point the issue did not anticipate: party information the protocol implies
RFC8152/Appendix_C_3_2putsPartyU identity,PartyV identityandSuppPubInfo.otherin the KDF context without sending any of them — "identity information is often known as part of the protocol and can thus be inferred rather than made explicit" (§5.2).RecipientLayer::withPartyU()/withPartyV()take aPartyInfothe application knows and complete what the headers carry, element by element, the headers winning where both have a value (PartyInfo::completedWith()).Acceptance criteria of #201
ecdh-direct-examples/,ecdh-wrap-examples/,hkdf-hmac-sha-examples/,hkdf-aes-examples/,aes-wrap-examples/,X25519-tests/andenveloped-tests/decrypt, multi-recipient and nested ones included (RFC8152/Appendix_C_5_4,Appendix_B); theCOSE_KDF_Context, the ECDHSecret_hex, theKEK_hexand theCEK_hexof every fixture match — the harness compares each of them beforerecoverKey()runs, and where the sending side is deterministic (AES-KW,direct+HKDF-*with a salt or nonce, ECDH-SS) it produces the recipient again and compares the ciphertext byte for byte. 194 skips become runs; the only fixtures still skipped are the three RSAES-OAEP ones.EC2key whose (x, y) is not on the curve is rejected before any scalar multiplication —EllipticCurveDiffieHellmanTest::aPointOnTheTwistIsRejectedBeforeAnyScalarMultiplicationwith a point on the quadratic twist of P-256 (y² = x³ + 9a·x + 27b, d = 3, verified in the test), refused by the library's own message;EcdhTest::anEphemeralKeyThatIsNotOnTheCurveIsRejectedfor the same point in a recipient; garbage points too.directrecipient with a non-emptyciphertext, a non-emptyprotectedbucket, or a sibling recipient is rejected —DirectTest, on both sides, nested recipients and a nil ciphertext as well.EncryptForTest::twoEncryptionsForTheSameRecipientProduceDifferentEphemeralKeys,EcdhTest::twoAgreementsForTheSameRecipientUseDifferentEphemeralKeys.Tests
tests/CoseWg/— the harness resolves the recipients of every fixture the way a receiver does (contentKey()→recoverKey()per wire recipient,keyEncryptionKeyOf()for the nested ones),CoseWgPartyexposesKEK_hex, the unsent party information and the supplementary information;directis now required like any algorithm on aCOSE_Mac/COSE_Encryptand still resolved by hand forCOSE_Mac0/COSE_Encrypt0, which carry no recipient.tests/Algorithm/KeyManagement/—HkdfTest(RFC 5869 A.1–A.3,hash_hkdf()equivalence, AES form against the fixture values, bounds),KdfContextTest(the exact encodings of five fixtures, int nonce,h'a0'),RecipientLayerTest,DirectTest,DirectHkdfTest(the four identifiers, salt ignored by AES and used by HMAC, salt-or-nonce rule, key restrictions),AesKeyWrapTest(RFC 3394 §4.1–4.6, every failure mode,wrap/unwrapkey_opsdistinct),EllipticCurveDiffieHellmanTest(fixture secrets on P-256 and X25519, agreement on all nine curves, the twist point, low-order X25519/X448 points, every mismatch),EcdhTest(the twelve identifiers × four curves round trip, the ES and SS fixtures, every rule),KeyManagementAlgorithmsTest(the set of eighteen, one family each, registry and enforcement).tests/Encryption/EncryptForTest.php,tests/Structure/KeyManagementHeadersTest.php(-1 to -3, -20 to -29, every type error),tests/Key/Ec2KeyPointValidationTest.php;RfcReferencesTestknows the eighteen;ExamplesTestruns the new example 05.Docs
README (This library implements, Features, new Key Management Algorithms section with the table, X.509 paragraph),
doc/Usage.md(intro, TOC, COSE_Encrypt (Multiple Recipients) withencryptFor()and the receiving side, new Key Management Algorithms section — the two sides, what each family enforces, ECDH-SS, the KDF context, key restrictions — the header parameter table for -1 to -29, examples and references),RELEASES.md,examples/README.md.Checks
Rebased on
4.9.xafter #212.phpstan(level max, no baseline change),ecs,rector,deptrac,parallel-lint,composer validate --strict: clean. PHPUnit: 2708 tests, 53 skipped on the 8.4 image (was 2434 / 194); 2702 / 74 on 8.2 with--prefer-lowest(the pre-existing Ed448/Brainpool skips of that image); 2708 / 53 on 8.5.Not in this PR
RSAES-OAEP (-40/-41/-42, RFC 8230 §3 — a separate issue, as #201 says), COSE-HPKE, sender-side nesting in
encryptFor()(one level; the example shows the second level by hand, the receiving side handles any depth), andMacStructurecounterparts ofencryptFor().