Skip to content

feat(key management): direct, AES-KW, HKDF, ECDH-ES/SS recipient algorithms (RFC 9053 §5–6) (#201) - #213

Merged
Spomky merged 5 commits into
4.9.xfrom
feat/issue-201-key-management
Sep 12, 2026
Merged

Spomky merged 5 commits into
4.9.xfrom
feat/issue-201-key-management

Conversation

@Spomky

@Spomky Spomky commented Sep 11, 2026

Copy link
Copy Markdown
Contributor

Target branch: 4.9.x
Resolves issue #201 (Closes #201)
Part of #202

  • It is a Bug fix
  • It is a New feature
  • Breaks BC
  • Includes Deprecations

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 the COSE_KDF_Context of §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) and protectKey(RecipientLayer, Key, ?string): ProtectedKey (sending) — plus isDirect().

Family Interface Classes Reference
Direct encryption DirectEncryption Direct (-6), DirectHKDF_SHA256 (-10), DirectHKDF_SHA512 (-11), DirectHKDF_AES128 (-12), DirectHKDF_AES256 (-13) §6.1
Key wrap KeyWrap (wrap(), unwrap(), keyLength()) A128KW (-3), A192KW (-4), A256KW (-5) over spomky-labs/aes-key-wrap §6.2.1
Key agreement KeyAgreement (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) §6.3.1, §6.4.1

RecipientLayer is what an algorithm runs against: the headers and ciphertext of the COSE_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.other and SuppPrivInfo. ProtectedKey is what the sending side returns: the key of the layer below, the header parameters to merge into the unprotected bucket (the ephemeral key), the recipient ciphertext.

What the issue asked, point by point

  • direct (-6) — RFC 9052 §8.5.1 enforced: protected MUST be zero-length (either empty form of §3 accepted, as for every recipient), ciphertext MUST be a zero-length bstr (nil refused too), recipients MUST be absent, only recipient of the message. Key type MUST be Symmetric (§6.1.1). No alg/key_ops enforcement: the key is the content key, the content algorithm checks it.
  • AES-KW (-3/-4/-5) — spomky-labs/aes-key-wrap ^7.0 added to require (it needs ext-mbstring; deptrac knows the AESKW\ 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.
  • HKDF (§5.1) — Hkdf is 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 untruncated AESMAC128_128 / AESMAC256_128 of 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. No ECDH + HKDF-AES exists.
  • COSE_KDF_Context (§5.2) — KdfContext + PartyInfo: [AlgorithmID, [id, nonce, other], [id, nonce, other], [keyDataLength, protected, ? other], ? SuppPrivInfo]; absent party fields are nil, never omitted; nonce is bstr / int; keyDataLength in bits; protected as carried or h'' when empty (emptyOrSerializedMap()); other / SuppPrivInfo only when the application defines them. Every Context_hex of the fixtures matches byte for byte, hmac-sha-256-13/14 (pub other, priv info) and RFC8152/Appendix_C_3_2 (identities known from the protocol, not sent) included.
  • ECDH (§6.3) — 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) check y² = x³ + ax + b and x, y < p before 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/d and nothing else.
    • ECDH-ES: the ephemeral key goes out as {1, -1, -2, -3} and comes in through CoseHeaders::getEphemeralKey(), which refuses a private part and a non-EC2/OKP type; a compressed y decompresses through feat(keys): COSE Key Thumbprint (RFC 9679) and compressed EC2 points #197.
    • ECDH-SS: the sender's static key is the application's to supply (withSenderKey(), private when sending, public when receiving, resolved from static key id or the *-sender parameters after the validation the application owns); a static key (-2) carried in the headers is used only when nothing was supplied. The sending side refuses to run without a salt or a PartyU nonce (§6.3.1); the receiving side derives with what the message carries — p256-ss-wrap-* of cose-wg carry neither.
    • key_ops MUST be empty on the public key of the agreement, MUST include derive key/derive bits on 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.
  • Header parameters — 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), with getEphemeralKey(), 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 the COSE_recipient array, adds the IV unless an IV or Partial IV is already there. Cose\Encryption\Recipient is the input (algorithm, key, headers; the alg is added where the family allows it: unprotected for direct and AES-KW, protected otherwise). A direct algorithm — direct, direct+HKDF-*, and also ECDH-*+HKDF-*, RFC 9052 §8.5.4 says the same of direct key agreement — refuses to coexist with another recipient.
  • examples/05-encrypt-recipients.php rewritten: 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_2 puts PartyU identity, PartyV identity and SuppPubInfo.other in 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 a PartyInfo the 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/ and enveloped-tests/ decrypt, multi-recipient and nested ones included (RFC8152/Appendix_C_5_4, Appendix_B); the COSE_KDF_Context, the ECDH Secret_hex, the KEK_hex and the CEK_hex of every fixture match — the harness compares each of them before recoverKey() 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.
  • An ephemeral EC2 key whose (x, y) is not on the curve is rejected before any scalar multiplication — EllipticCurveDiffieHellmanTest::aPointOnTheTwistIsRejectedBeforeAnyScalarMultiplication with 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::anEphemeralKeyThatIsNotOnTheCurveIsRejected for the same point in a recipient; garbage points too.
  • A direct recipient with a non-empty ciphertext, a non-empty protected bucket, or a sibling recipient is rejected — DirectTest, on both sides, nested recipients and a nil ciphertext as well.
  • Two encryptions of the same plaintext for the same ECDH-ES recipient produce different ephemeral keys — 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), CoseWgParty exposes KEK_hex, the unsent party information and the supplementary information; direct is now required like any algorithm on a COSE_Mac / COSE_Encrypt and still resolved by hand for COSE_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/unwrap key_ops distinct), 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; RfcReferencesTest knows the eighteen; ExamplesTest runs 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) with encryptFor() 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.x after #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), and MacStructure counterparts of encryptFor().

…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.
@Spomky Spomky added this to the 4.9.0 milestone Sep 11, 2026
@Spomky Spomky added enhancement New feature or request dependencies Pull requests that update a dependency file compliance Issue related to the compliance of the project with the specs algorithms Signature, MAC, encryption and key-management algorithms headers Header parameters and message structures keys COSE_Key types, parameters and thumbprints documentation README, doc/ and examples/ tests Test suite, fixtures and interoperability vectors labels Sep 11, 2026
@Spomky Spomky self-assigned this Sep 11, 2026
@Spomky
Spomky merged commit 1ada702 into 4.9.x Sep 12, 2026
17 checks passed
@Spomky
Spomky deleted the feat/issue-201-key-management branch September 12, 2026 07:40
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

algorithms Signature, MAC, encryption and key-management algorithms compliance Issue related to the compliance of the project with the specs dependencies Pull requests that update a dependency file documentation README, doc/ and examples/ enhancement New feature or request headers Header parameters and message structures keys COSE_Key types, parameters and thumbprints tests Test suite, fixtures and interoperability vectors

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(key management): direct, AES-KW, HKDF, ECDH-ES/SS recipient algorithms (RFC 9053 §5–6)

1 participant