@blamejs/pki 0.6.54 → 0.6.55

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -4,6 +4,35 @@ All notable changes to `@blamejs/pki` are documented here. The format
4
4
  follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); this
5
5
  project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
6
 
7
+ ## v0.6.55 — 2026-09-07
8
+
9
+ A Diffie-Hellman key proves possession by agreeing a secret with the authority, without signing anything.
10
+
11
+ ### Added
12
+
13
+ - pki.crmf.build assembles the agreeMAC proof of possession (RFC 4211 section 4.3, RFC 2875 section 3). The requester supplies pop.key, its own Diffie-Hellman private key, and pop.caCert, the authority's certificate it already holds; the two agree a secret, a key is derived from it, and that key MACs the request. The proof carries id-dhPop-static-HMAC-SHA1, and both that OID and id-alg-dhPOP are registered.
14
+ - The proof value is the DhPopStatic structure section 3 defines, not the bare MAC: the BIT STRING carries a SEQUENCE of the issuer name and serial number of the certificate the authority's key came from, and the HMAC result as an OCTET STRING. The section says so after the computation it describes, "i.e. encodes the above sequence instead of the raw output from 3d".
15
+ - The key is derived as RFC 2875 section 3 states it: SHA-1 over the authority certificate's subject name, the agreed secret, and its issuer name, in that order. Section 4.3 settles which certificate those names come from and what to do when one is absent, so an authority certificate whose subject name is empty contributes its subjectAltName instead, and one carrying neither is refused rather than keyed from nothing. That alternative name is read as the GeneralNames it is rather than measured, since the certificate parser surfaces an extension's bytes without running the decoder registered for it: an empty list carries a length while naming nobody, and so does one holding a value that no arm of the GeneralName choice covers. The three arms the shared name reader takes on their tag or admits empty are read further: an x400Address must open with the standard attributes an ORAddress begins with, rather than with whatever value carries that tag, and must name somebody in one of its components, every built-in field being optional so that naming data can sit in the domain-defined or extension attributes instead; a directoryName wrapping a Name of no relative names substitutes an empty name for the empty name that reached this fallback, and an ediPartyName is read down to the strings it names a party with, a DirectoryString being one of five string types carrying at least one character. A party named with an empty string, or with bytes that are not the encoding their tag claims, names nobody either. Section 4.3 states the same fallback for an empty issuer name, which a certificate reaching this proof cannot carry: RFC 5280 section 4.1.2.4 requires a non-empty issuer, and the certificate parser enforces it.
16
+ - The MAC covers the DER certReq, and the request must name both a subject and a public key. Section 4.3's own ASN.1 comment states both, where the prose states neither: the proof is "a MAC (over the DER-encoded value of the certReq parameter in CertReqMsg, which must include both subject and publicKey)". A template naming only one of them is refused.
17
+ - pop.key must be the private half of certTemplate.publicKey. The authority derives its side of the agreement from the requested key, so a private key from another pair agrees a secret with the authority and yields a MAC the authority cannot reproduce: a proof of possession of something the request never asked to have certified. The encryptedKey arm holds its enclosed key to the same rule.
18
+ - The proof is admitted only for a finite-field Diffie-Hellman pair, which is what section 3 defines it over, and only when the requester's key can actually reach the authority's, which section 4.3 requires. An elliptic-curve or montgomery pair agrees a secret through the same operation and is refused rather than emitted under an OID naming something the recipient is not performing; so is a key on another group, and a key this runtime cannot classify is named as unrecognized rather than reported as a key type. Every copy of private material the proof allocates is cleared before the call returns, on the refusing paths as well as the building one: the agreed secret, the key derived from it, and the copy taken of the caller's key. The caller's own key is left untouched.
19
+ - Every key this proof touches is read in both encodings a finite-field key is written in. An X.509 Diffie-Hellman certificate names dhpublicnumber and carries X9.42 DomainParameters (RFC 3279 section 2.3.3) where this runtime classifies only the PKCS#3 form, so such a key is rewritten into the form it reads: the authority's certificate, the requested key, the enclosed key an encryptedKey proof archives and the public half derived from it, and the requester's own private key, which is a PKCS#8 whose algorithm is rewritten while the private value it wraps is unchanged. That private key is taken in every form the verb accepts it in: DER, a PEM block, and a key object the runtime holds without classifying, since admitting one of the three is not supporting the encoding. The request still carries the encoding the caller asked to have certified.
20
+ - Whether a set of parameters describes the key it carries is asked of every key read, in either encoding, since a request carries those parameters on to whoever reads it next. The modulus must be prime, and the public value must lie inside the group. Where the certificate states a subgroup order, that order must divide p-1, must be an order the generator actually has, must be prime, and must hold the public value; where a cofactor is given with it, the two must account for p. The requester's own private key is read the same way, since the PKCS#3 form it is rewritten into carries neither the order nor the cofactor and that rewrite is the last place either is looked at. A PrivateKeyInfo states no public value, so the two tests that hold one to these parameters are the only ones it is not held to.
21
+ - These rules govern a key a secret is agreed with. The encryptedKey arm asks the one question RFC 4211 section 4.2 states, whether the enclosed key is the private half of the requested one, and agrees nothing, so it reads both encodings for their shape and does not measure the group: whether a key sits in a good group is the certifying authority's policy, and answering it here would mean proving a modulus prime, which costs seconds and bounds the size, so a key too large to prove would become a key too large to archive. A legacy group and a group larger than any agreement would accept both still enroll there. What a stated order and cofactor say about the p and g beside them is a separate question, and that arm answers it: the conversion drops both while the request goes out carrying the caller's own encoding of them, and the tests are a multiplication and a modulo rather than the exponentiation and the primality proofs the size bound exists for.
22
+ - Both exponents this agreement uses must be ones the other side cannot work out. RFC 2631 section 2.2 states X9.42's own requirement, that the private key lie in the interval [2, q-2], and the exponents outside it agree a secret that follows from values the request and the authority certificate already carry: zero agrees one, one agrees the other side's public value itself, and the order less one agrees the inverse of that value. A MAC keyed from any of them proves possession of nothing. The requester's key and the authority's are held to it alike, since an agreement has two exponents and either one outside the interval makes the secret public.
23
+ - The rule is read through the group's own order. A safe prime also has elements of order 2q, and the PKCS#3 form states no order, so a generator of that full order is admitted; its square root of one reflects each excluded value, so the exponent q+1 produces p minus g and q-1 produces p minus the inverse of g. Each agrees the negation of a secret that already follows, so the reflections are excluded with the values they reflect. An exponent that is merely small is a different matter and is not tested: it cannot be read off the public value without solving a discrete log, no specification states a floor for it, and the interval admits it. The test reads the public value each key states rather than the key itself, so it needs no copy of private material and no stated order.
24
+ - The floors are the strength the agreement itself needs. A stated order must be large enough to hide an exponent: a prime order makes the public value's order exactly that value rather than a divisor of it, which is worth nothing when the value is small, and three is prime. The floor is the smallest subgroup order NIST SP 800-56A states for a finite-field group. Where no order is stated, which the PKCS#3 form cannot, the modulus must be a safe prime, whose element orders are one, two, r and 2r alone, and that order carries the same floor, since seven is a safe prime whose own subgroup has order three. The modulus carries a floor of 2048 bits, the size the toolkit's linter already names for a public key: a large subgroup says a value is hard to take a discrete log of inside the group and says nothing about the group itself, and a 512-bit safe prime has a 255-bit subgroup while the secret agreed in it is recoverable. A 1024-bit legacy group no longer completes this proof. Proving a modulus prime costs from a fraction of a second over a 2048-bit group to a second or two at the 4096-bit bound, and the answers are remembered, so a run of requests against one authority proves its group once.
25
+ - The one optional field a PKCS#3 DHParameter carries is held to the modulus beside it. privateValueLength states how many bits the private value has, and a private value is less than the modulus, so a length above the modulus's own bit count describes no value the group holds; it was read for being a positive integer and carried through unchanged, so a request could travel stating one. The encoded size bounds the count before anything is shifted by it, since the field is an INTEGER the codec admits at any width.
26
+ - A refusal names the key it is about. The authority certificate, the requested key, the requester's private key and the enclosed private key each reported as the authority certificate's, whichever one the reader had been handed.
27
+ - The parameters are sized before anything is computed with them, since these tests raise one operand to the power of another and prove a modulus prime, while the DER reader admits an integer far wider than any Diffie-Hellman group. The bound is 4096 bits, which covers every MODP group a certificate carries. Every container is read for the tag it carries rather than for having children, so a context-specific constructed value in place of the DomainParameters SEQUENCE is refused rather than rewritten into a key that imports while the request carries the original. The cofactor and the validation parameters are each optional and independent, so a fourth field is read by its tag: the cofactor is held against p and q, and the validation parameters against the seed BIT STRING and pgenCounter INTEGER they consist of. The public key BIT STRING must hold whole octets, since the codec admits a nonzero unused-bit count whose padding bits are zero and that BIT STRING is carried through unchanged.
28
+ - The authority certificate's keyUsage is enforced. A keyUsage extension restricts the certified key to the purposes it asserts (RFC 5280 section 4.2.1.3), and this proof uses the authority's key to agree a secret, so a certificate that states its purposes without stating keyAgreement is refused rather than used for it. A certificate carrying no keyUsage states no restriction and is unaffected.
29
+
30
+ ### Fixed
31
+
32
+ - A constructed DER value is written into one allocation. Building a SEQUENCE or a SET concatenated the children and then concatenated that with the header, leaving an intermediate holding everything the children carry; where a structure is built over private material, that intermediate was a copy of it no caller could reach to clear. pki.asn1.build.sequence, .set and .setOf now assemble directly, which covers every caller rather than the ones that remembered to. The encoding is unchanged, byte for byte. Clearing a key's copies is still best effort, since a runtime copies buffers where no code can reach them.
33
+ - pki.sigstore.verifyBundle refuses a bundle that carries both content arms. A bundle setting dsse_envelope and message_signature together was verified on the envelope alone, returning a verdict that said nothing about the other arm the bundle carried. The bundle's content is a oneof, so exactly one arm may be present and both is now sigstore/bad-bundle.
34
+ - The same rule holds for verificationMaterial, whose certificate, x509CertificateChain and publicKey are a oneof of the same kind. More than one arm set drew the leaf certificate from one and the chain it is validated through from another, so the certificate whose key was checked and the certificates it was checked through came from different statements about the same signer, and a publicKey beside either certificate arm named a second signer identity the verdict said nothing about.
35
+
7
36
  ## v0.6.54 — 2026-09-07
8
37
 
9
38
  A holder of a composite ML-KEM key can enroll for it, proving possession by opening the challenge addressed to it.
package/README.md CHANGED
@@ -234,7 +234,7 @@ comment blocks, is at [pkijs.com](https://pkijs.com).
234
234
  | `pki.x509` | Certificate issuance (RFC 5280 §4). `sign(spec, issuer, opts)` builds and signs a certificate from a `spec` of subject (a common-name string, an array of RDNs, or raw Name DER), the public key being certified, the validity window, an optional serial, and an optional `extensions` object. The `issuer` is a key alone (self-signed: issuer equals subject, signed with that key), a name plus public key plus key, or an issuing certificate plus key. The signature algorithm is resolved from the signing key through the shared registry, so RSA (PKCS#1 v1.5 or PSS via `opts.pss`), ECDSA P-256/384/521, Ed25519, Ed448, ML-DSA-44/65/87, the twelve SLH-DSA sets, and the composite arms all issue without a per-algorithm branch. It encodes basic constraints, key usage, extended key usage, subject and authority key identifiers (the SKI derived by SHA-1 of the subject key), subject alternative names, and certificate policies from the spec, taking any other extension as pre-encoded DER. It derives the version from the field set and enforces the serial bounds, the UTCTime/GeneralizedTime cutover, the DER default omissions, and the CA cross-field rules; a violation throws a typed `CertificateError`. Returns DER, or a PEM `CERTIFICATE` with `opts.pem`. Every arm is independently verified by OpenSSL. Parsing stays at `pki.schema.x509.parse` — `sign` |
235
235
  | `pki.csr` | PKCS#10 certification-request issuance (RFC 2986 / RFC 2985). `sign(spec, key, opts)` builds and signs a `CertificationRequest` from a `spec` of subject (which may be empty), the public key being certified, an optional `extensionRequest` carrying the requested v3 extensions a CA copies into the issued certificate (subject alternative names, key usage, extended key usage, basic constraints, certificate policies, subject key identifier, or an array of pre-encoded Extension DER), and an optional `challengePassword`. `key` (or `{ key }`) is the subject's own private key: the request is self-signed to prove possession of the private half of `subjectPublicKey`, and that proof is verified before the request is returned, which is what `openssl req -verify` checks. The signature algorithm is resolved from the subject key, so RSA (PKCS#1 v1.5 or PSS via `opts.pss`), ECDSA, EdDSA, ML-DSA, SLH-DSA, and the composite arms all sign without a per-algorithm branch. Returns DER, or a PEM `CERTIFICATE REQUEST` with `opts.pem`; malformed input throws a typed `CsrError`. `verify(request)` asks the same question of a request someone else produced, over its exact signed `certificationRequestInfo` bytes under the `subjectPKInfo` inside them, through the one path-validation signature engine. It answers `{ verified, subject, subjectPublicKeyInfo, attributes, certificationRequestInfoBytes }`, all re-derived from the signed bytes, so a CA issues from the fields the signature covers rather than from the object it passed in. A `verified: true` says the producer held that private key and that the subject and requested extensions are the ones they signed; who they are is the enrollment protocol's question, not this one. Parsing stays at `pki.schema.csr.parse` — `sign`, `verify` |
236
236
  | `pki.attrcert` | Attribute-certificate issuance (RFC 5755). `sign(spec, issuer, opts)` builds and signs an `AttributeCertificate` as an Attribute Authority: a `spec` of `holder` (exactly one of an entity name, a `baseCertificateID` reference, a `fromCertificate` binding, or an object digest), the validity window as GeneralizedTime, an optional serial (positive, at most 20 octets, randomly generated when omitted), the `attributes` (role, clearance, group, chargingIdentity, accessIdentity, authenticationInfo, or pre-encoded Attribute DER), and optional `extensions` (auditIdentity, targetInformation, noRevAvail, aaControls, acProxying, authorityKeyIdentifier, or pre-encoded Extension DER) each with its RFC 5755 criticality. An attribute certificate is never self-signed, so the `issuer` is the signing AA, supplied as `{ cert, key }` or `{ name, publicKey, key }`. The signature algorithm is resolved from the AA key, so RSA (PKCS#1 v1.5 or PSS via `opts.pss`), ECDSA, EdDSA, ML-DSA, SLH-DSA, and the composite arms all sign without a per-algorithm branch, and the signature is verified under the AA public key before the certificate is returned. Returns DER, or a PEM `ATTRIBUTE CERTIFICATE` with `opts.pem`; malformed input throws a typed `AttrCertError`. `verify(ac, issuer, opts)` is the receiving side, performing the RFC 5755 sec. 5 checks an attribute certificate and a named issuer can settle between them: the signature over the exact `AttributeCertificateInfo` bytes through the one path-validation signature engine, the AC naming the issuer this verifier trusts (compared as a distinguished name), the evaluation instant lying within the validity with equality at either bound succeeding as the section states, the sec. 4.3.2 targeting rule, and rejection of any critical extension this verb does not process (section 5 defines support as parsing the value AND rejecting where the value would reject, so `aaControls` and `acProxying`, whose constraints it does not evaluate, are refused when critical). It answers `{ verified, signatureValid, validityChecked, targetingChecked, holderBindingChecked, issuerPathChecked, holder, issuer, attributes, extensions, notBefore, notAfter, serialNumberHex, reason }` with the fields re-derived from the signed bytes; the holder's own certificate chain and the AC issuer's chain need certificates the verb is not given, so those slots report `false` rather than letting their absence read as a pass. Parsing stays at `pki.schema.attrcert.parse` — `sign`, `verify` |
237
- | `pki.crmf` | Certificate-request-message issuance (RFC 4211). `build(spec, key, opts)` assembles a `CertReqMessages` from a `spec` of `certReqId` (default 0, with the RFC 9483 `-1` sentinel allowed), a `certTemplate` of the requested fields (`subject`, `publicKey` as the SPKI DER of the key being certified, `validity`, requested `extensions`, an optional `version` 2), optional `controls` and `regInfo` (regToken, authenticator, utf8Pairs, oldCertID, protocolEncrKey, or pre-encoded `AttributeTypeAndValue` DER), and an optional `pop` selector. `key` (or `{ key }`) is the requester's private key: the message carries a `POPOSigningKey` proof of possession signed with the private half of `certTemplate.publicKey` and verified before the message is returned, exactly as a PKCS#10 CSR proves possession. A complete template signs the `CertRequest`; an incomplete one signs a `POPOSigningKeyInput`. The signature algorithm is resolved from the requested public key, so RSA (PKCS#1 v1.5 or PSS via `opts.pss`), ECDSA, EdDSA, ML-DSA, SLH-DSA, and the composite arms all sign without a per-algorithm branch. `key` is optional for a `raVerified` proof. A key that cannot sign, which is where an ML-KEM enrollment sits, takes a `POPOPrivKey` proof instead (RFC 4211 sec. 4.2, sec. 4.3): `pop.type` of `keyEncipherment` or `keyAgreement` with `pop.method: 'subsequentMessage'` declares whether an encrypted certificate (`encrCert`) or a challenge (`challengeResp`) completes the proof over the enrolling protocol's next exchange, and `pop.method: 'encryptedKey'` encloses the requester's private key for the CA in a CMS `EnvelopedData` under `id-ct-encKeyWithID`, requiring `pop.privateKey`, `pop.recipients`, the `pop.identifier` sec. 4.2.1 makes mandatory, and `pop.archive: true` because RFC 9810 sec. 5.2.8.3.1 permits the method only where archival is intended. The enclosed key must be the private half of `certTemplate.publicKey`, or the proof demonstrates possession of a key the request never asked to have certified. The `thisMessage` and `dhMAC` alternatives the specification deprecates are refused with their successors named, and `agreeMAC` is not built, since it needs the RFC 2875 static Diffie-Hellman secret against a CA certificate the requester already holds. Pass an array of specs for a batch; the CA-assigned template fields are never emitted. Returns DER, or a PEM block with `opts.pem`; malformed input throws a typed `CrmfError`. `verifyPop(messages)` is the receiving side: for each `CertReqMsg` it verifies the `POPOSigningKey` signature over the bytes RFC 4211 sec. 4.1 names — the DER of `poposkInput` when present, of `certReq` when not — through the one path-validation signature engine, and answers `{ verified, messages: [{ verified, method, cryptographicallyVerified, certReqId, subject, subjectBound, publicKey, reason }] }` with the fields re-derived from the message's own bytes. Each verdict reports only what its preimage covers: `publicKey` is the key possession was proven for, and `subject` is the requested name when the `certReq` was signed. A `poposkInput` preimage covers the key and the sender alone, so any subject beside it is unsigned and is withheld with `subjectBound: false`. A `raVerified` proof is an RA's out-of-band assertion and a `keyEncipherment` or `keyAgreement` proof completes over a later exchange, so each is reported unverified with its `method` named instead of guessed. Parsing stays at `pki.schema.crmf.parse` — `build`, `verifyPop` |
237
+ | `pki.crmf` | Certificate-request-message issuance (RFC 4211). `build(spec, key, opts)` assembles a `CertReqMessages` from a `spec` of `certReqId` (default 0, with the RFC 9483 `-1` sentinel allowed), a `certTemplate` of the requested fields (`subject`, `publicKey` as the SPKI DER of the key being certified, `validity`, requested `extensions`, an optional `version` 2), optional `controls` and `regInfo` (regToken, authenticator, utf8Pairs, oldCertID, protocolEncrKey, or pre-encoded `AttributeTypeAndValue` DER), and an optional `pop` selector. `key` (or `{ key }`) is the requester's private key: the message carries a `POPOSigningKey` proof of possession signed with the private half of `certTemplate.publicKey` and verified before the message is returned, exactly as a PKCS#10 CSR proves possession. A complete template signs the `CertRequest`; an incomplete one signs a `POPOSigningKeyInput`. The signature algorithm is resolved from the requested public key, so RSA (PKCS#1 v1.5 or PSS via `opts.pss`), ECDSA, EdDSA, ML-DSA, SLH-DSA, and the composite arms all sign without a per-algorithm branch. `key` is optional for a `raVerified` proof. A key that cannot sign, which is where an ML-KEM enrollment sits, takes a `POPOPrivKey` proof instead (RFC 4211 sec. 4.2, sec. 4.3): `pop.type` of `keyEncipherment` or `keyAgreement` with `pop.method: 'subsequentMessage'` declares whether an encrypted certificate (`encrCert`) or a challenge (`challengeResp`) completes the proof over the enrolling protocol's next exchange, and `pop.method: 'encryptedKey'` encloses the requester's private key for the CA in a CMS `EnvelopedData` under `id-ct-encKeyWithID`, requiring `pop.privateKey`, `pop.recipients`, the `pop.identifier` sec. 4.2.1 makes mandatory, and `pop.archive: true` because RFC 9810 sec. 5.2.8.3.1 permits the method only where archival is intended. The enclosed key must be the private half of `certTemplate.publicKey`, or the proof demonstrates possession of a key the request never asked to have certified. The `thisMessage` and `dhMAC` alternatives the specification deprecates are refused with their successors named. `pop.method: 'agreeMAC'` completes the four: `pop.key` is the requester's finite-field Diffie-Hellman private key, as a PKCS#8 DER, a PEM `PRIVATE KEY` block or a `KeyObject`, and `pop.caCert` the authority's certificate it already holds; the two agree a static secret (RFC 2875 sec. 3), and the key derived from it MACs the DER `certReq` under `id-dhPop-static-HMAC-SHA1`. Either key may name its group in the PKCS#3 or the X9.42 encoding. `pop.key` must be the private half of `certTemplate.publicKey`, and the template must name both a subject and a public key. Pass an array of specs for a batch; the CA-assigned template fields are never emitted. Returns DER, or a PEM block with `opts.pem`; malformed input throws a typed `CrmfError`. `verifyPop(messages)` is the receiving side: for each `CertReqMsg` it verifies the `POPOSigningKey` signature over the bytes RFC 4211 sec. 4.1 names — the DER of `poposkInput` when present, of `certReq` when not — through the one path-validation signature engine, and answers `{ verified, messages: [{ verified, method, cryptographicallyVerified, certReqId, subject, subjectBound, publicKey, reason }] }` with the fields re-derived from the message's own bytes. Each verdict reports only what its preimage covers: `publicKey` is the key possession was proven for, and `subject` is the requested name when the `certReq` was signed. A `poposkInput` preimage covers the key and the sender alone, so any subject beside it is unsigned and is withheld with `subjectBound: false`. A `raVerified` proof is an RA's out-of-band assertion and a `keyEncipherment` or `keyAgreement` proof completes over a later exchange, so each is reported unverified with its `method` named instead of guessed. Parsing stays at `pki.schema.crmf.parse` — `build`, `verifyPop` |
238
238
  | `pki.cmp` | CMP message building, transfer, and verification (RFC 9810). `build(message, opts)` assembles a protected `PKIMessage`. `message.header` carries the `sender` and `recipient` GeneralNames (including the anonymous NULL-DN) plus optional transaction metadata; `message.body` is a single-key object naming the arm — request-side `ir`, `cr`, `kur`, `krr` (key recovery, §5.3.7), `ccr` (cross-certification, §5.3.11: a `CertReqMessages` at the normative floor, where the requesting CA keeps its private key so a private-key-transport encryptedKey proof-of-possession is refused, and the optional App. D.6 single-request cardinality is not enforced), `p10cr`, `certConf`, `pollReq`, `genm`, `rr`, responder-side `ip`, `cp`, `kup`, `ccp`, `rp`, `genp`, `error`, `pollRep`, `krp`, `pkiconf`, and the registration-authority `nested` wrapper of complete PKIMessages (RFC 9810 §5.1.3.5). Protection is exactly one of `opts.{ key, cert }`, a signature under the sender key with the algorithm resolved from the signer certificate so RSA (PKCS#1 v1.5 / PSS), ECDSA, EdDSA, ML-DSA, SLH-DSA, and the composite arms all sign without a per-algorithm branch, `opts.mac`, a PBMAC1 shared-secret HMAC (RFC 9481 / 9579, PBKDF2-derived), or `opts.kem`, a KEM-based MAC for a client whose key can only establish secrets (RFC 9810 §5.1.3.4): the ciphertext a peer encapsulated to its ML-KEM key is decapsulated, the key is derived under HKDF-SHA256 with a context bound to the transaction identifier of the message that carried the ciphertext, and `pki.cmp.verify` checks it from the shared secret. Protection covers the exact DER of the virtual `ProtectedPart` and is self-verified before the message is returned, and `protectionAlg` is derived rather than caller-set, so the message the parser accepts is coherent by construction. A `p10cr` request's PKCS#10 proof-of-possession is verified before the message is protected, so one whose self-signature does not verify under its subject public key is refused rather than sent. `transfer(url, message, opts)` carries a built message to a CMP endpoint over `pki.transport` (RFC 9811): one POST of the DER PKIMessage, with the response classified fail-closed — 200 only for success, a non-200 2xx or an un-followed 3xx refused, a 4xx or 5xx carrying a CMP error PKIMessage forwarded as the integrity-protected verdict — and protection surfaced rather than verified. `wellKnownUrl(base, opts)` builds the §3.4 `/.well-known/cmp` request-URIs. `verify(message, opts)` checks the protection on an incoming message, either a signature through the same certification-path engine `pki.crl.verify` and `pki.ocsp.verify` use, with the EdDSA low-order-point and algorithm-confusion gates, or a PBMAC1 MAC recomputed from `opts.sharedSecret` and the message's own PBKDF2 parameters and constant-time compared, over the exact `ProtectedPart` reconstructed from the parser's raw slices. It is fail-closed on an unprotected message, a legacy or KEM MAC algorithm, an omitted keyLength, or a SHA-1 PRF, and returns a `{ valid, trusted, protectionType, signer, ... }` verdict. With `opts.trustAnchors` the signer certificate is fully path-validated (RFC 5280 §6.1 plus the RFC 9483 §3.2 `keyUsage.digitalSignature` gate) at a trusted current time, or an explicit `opts.time` for historical verification and never the message's self-asserted `messageTime`, before it is reported trusted; without one the verdict is crypto-only and the signer certificate is surfaced to anchor. `session(opts)` returns a stateful enrollment session whose `enroll(request)` drives a full `ir` / `cr` / `kur` / `p10cr` transaction over the shared transport, composing `build`, `transfer`, and `verify`. Every response is protection-verified, signer-trusted, and bound to the exchange (a stable `transactionID`, a fresh-`senderNonce` and echoed-`recipNonce` chain) before its body is read, with a bounded `pollReq` / `pollRep` loop for a `waiting` status and a `certConf` / `pkiConf` (or implicit) confirmation carrying an explicit `hashAlg` for a signature algorithm that does not convey its hash. It returns a terminal `{ outcome, certificate, chain, status, trusted, confirmed, implicitConfirm, transactionID, polls, transcript }`. A certification authority can take longer to answer than a process is held open, so a `poll-timeout` carries a `resumeToken` and `resumePoll(token)` continues the same transaction in a later process: the token is plain JSON naming the transaction, the nonce the next request echoes, the polled request and the arm its grant arrives on, and the key the grant must certify. It carries no secret and grants nothing, since the protection material and the endpoint come from the session built to resume with, and the resumed poll verifies, nonce-binds, and key-binds every response. Its fields are what the resumed exchange is held to, so store it where the enrollment's own state is stored: someone who can rewrite it can widen what the resumed session accepts, as far as that session's trust anchors and the authority's protection allow and no further. The same session also drives the other two RFC 9483 operations under that shell: `revoke(request)` sends an `rr` naming a certificate as `{ certificate }` or `{ certDetails }` with an optional CRLReason `reason`, and returns `revoked` / `rejected` / `poll-timeout`; `info(request)` sends a `genm` for one of the four support messages — `{ caCerts }`, `{ rootCaCert }`, `{ certReqTemplate }`, `{ crlUpdate }` — and returns `answered` with the decoded `value` and a `present` flag, since an absent response value is how each says nothing is available. A session revokes its own certificate: the signature over the request is the proof of authorization (§4.2), so the named certificate must be `opts.cert` and a PBMAC1 session is refused. The signature flavor requires `opts.trustAnchors` to authenticate the CA; a verified rejection or error and an exhausted poll budget are terminal verdicts, while a tampered, untrusted, or desynchronized response is a typed throw. Returns DER, or a PEM `CMP` block with `opts.pem`; malformed input throws a typed `CmpError`. `openKeyPackage(container, opts)` opens a private key the CA generated centrally and delivered in the `privateKey` field of a granted `CertifiedKeyPair` (RFC 9483 §4.1.6): a CMS `SignedData` over an RFC 5958 `AsymmetricKeyPackage`, sealed in a CMS `EnvelopedData`. `opts.key` (with `opts.cert`) opens the key transport and key agreement containers a signature-protected request selects, `opts.password` the password container a MAC-protected request selects. The authority is authorized before any key material is returned: its certificate must chain to an anchor in `opts.trustAnchors` AND assert the `id-kp-cmKGA` extended key usage, since a certificate with no `extendedKeyUsage` permits every purpose and so authorizes nothing; `opts.authorizedBySharedSecret` states §4.1.6's exemption for an entity that authorizes by the secret that protected its request. Returns `{ keys, kga, trusted }`, where each key is a PKCS#8 `PrivateKeyInfo` ready for `pki.key.import`; `keys` is the whole RFC 5958 `AsymmetricKeyPackage` (`SIZE (1..MAX)`), while a session enrollment requires the sequence of one §4.1.6 profiles it to. Both CMS layers are read as a ContentInfo or as the bare structure, told apart by what the SEQUENCE opens with. `session(opts)` drives the whole exchange under `opts.acceptCentralKeyGeneration`: the request omits `certTemplate.publicKey`, carries no proof of possession, and goes out as `cmp2021`; the session opens the delivered container with the credential it enrolled under and surfaces it as `deliveredKey`, having first checked that the issued certificate certifies the delivered key. Without the option, such a request and such a grant are both refused. Parsing stays at `pki.schema.cmp.parse` — `build`, `transfer`, `wellKnownUrl`, `verify`, `openKeyPackage`, `session` |
239
239
  | `pki.crl` | CRL issuance and verification (RFC 5280 §5). `sign(spec, issuer, opts)` builds and signs a `CertificateList` from a `spec` of `thisUpdate` and `nextUpdate`, an optional `crlNumber`, a `revoked` array (each entry a `serialNumber` and `revocationDate` with an optional `reason` or `invalidityDate`), and an optional `extensions` object (authority key identifier, issuing distribution point, delta-CRL indicator, freshest CRL, authority information access) or an array of pre-encoded Extension DER, with an `issuer` of `{ cert, key }` or `{ name, publicKey, key }`. The signature algorithm is resolved from the issuer key, so RSA (PKCS#1 v1.5 or PSS via `opts.pss`), ECDSA, EdDSA, ML-DSA, SLH-DSA, and the composite arms all sign without a per-algorithm branch. The version is derived from the extension set (v2 when any CRL or entry extension is present, else v1), the outer `signatureAlgorithm` matches `tbsCertList.signature`, an empty revocation list omits the field rather than emitting an empty SEQUENCE, `reasonCode` is an ENUMERATED and `invalidityDate` is always GeneralizedTime, the RFC fixes per-extension criticality, and the produced signature is verified under the issuer key before return. `verify(crl, issuer)` checks a CRL signature through the one path-validation signature engine, algorithm-confusion and EdDSA low-order gates included; handed a certificate rather than a bare key it also asks what only a certificate can answer — that the certificate is the issuer the CRL names, and that its `keyUsage`, when present, asserts `cRLSign` — so a CRL minted under an end-entity certificate of the same CA does not verify as that CA's. `isRevoked(crl, serialNumber, opts)` looks a serial up, and first checks that the CRL is one a serial can be looked up in at all — it is handed a serial and nothing else, so a CRL that speaks for part of its issuer's certificates is refused rather than answered from. A delta CRL lists changes since a base, so an entry recording a release reads as a revocation when read alone; an indirect CRL carries other issuers' entries, whose serials are unrelated to yours; and any other `issuingDistributionPoint` narrows the CRL to one distribution point, one kind of certificate, or a subset of revocation reasons, none of which a serial can be matched against. A CRL speaks for a span as well as a set, so `opts.time` states the instant the question is asked at and a list that has stopped speaking for it — `nextUpdate` passed, `thisUpdate` later, or no `nextUpdate` stated at all — is refused rather than read as a clean bill of health; without `opts.time` the lookup is structural and an absent serial means only that it is not on that list. `pki.path.crlChecker` is the verb for all of them: it is handed the certificate, merges a delta with its base, performs the §6.3.3 correspondence, and decides currency against the material it fetched. Returns DER, or a PEM `X509 CRL` with `opts.pem`; malformed input throws a typed `CrlError`. Parsing stays at `pki.schema.crl.parse` — `sign`, `verify`, `isRevoked` |
240
240
  | `pki.key` | Key-material lifecycle (RFC 5958 / RFC 8018). `encrypt(privateKey, password, opts)` wraps a PKCS#8 private key (DER, PEM, or an extractable `CryptoKey`) into an `EncryptedPrivateKeyInfo` under PBES2 (PBKDF2 with AES-CBC-Pad), where `opts` selects the `cipher` (`aes-256-cbc` default, `aes-192-cbc`, `aes-128-cbc`), the `prf` (`hmacWithSHA256` default, SHA-384/512, SHA-1), the `iterations` (default 600000), and the `salt`. The plaintext is validated as PKCS#8 before encryption, a default `prf` and `keyLength` are omitted so the parameters are byte-exact with OpenSSL, and the output is re-parsed before return. `decrypt(encrypted, password, opts)` recovers the inner `PrivateKeyInfo`, re-validated through `pki.schema.pkcs8.parse`: only PBES2 / PBKDF2 / AES-CBC is accepted (PBES1, PBMAC1, and scrypt are refused), the salt and iteration count are bounded before any derivation (`opts.maxIterations` lowers the cap), and a malformed parameter set or wrong-length IV is a distinct typed error. Because a MAC-less PBES2-CBC decrypt must not become a padding oracle (RFC 8018 §8), a wrong password and a valid-pad-but-not-a-key both surface the one uniform `key/decrypt-failed`. `export(key, opts)` and `import(input, opts)` move a private key as PKCS#8 or a public key as SubjectPublicKeyInfo. The key may come from the platform's WebCrypto or from a separately installed copy of this toolkit, and is exported through whichever holds its material; a non-extractable key, or one whose implementation keeps its material out of reach, is refused with that as the reason. Encoding is delegated to WebCrypto, so RSA carries an explicit NULL, EC a named curve, and Ed25519/Ed448/X25519/X448 omit parameters, and an ambiguous RSA or EC import requires `opts.algorithm`. `generate(algorithm, opts)` produces a key pair over RSA, ECDSA/ECDH, the Edwards and Montgomery curves, and the FIPS post-quantum ML-DSA and ML-KEM; `publicFromPrivate(privateKey)` derives the public key. Returns DER or PEM, with a typed `KeyError` on failure. Parsing stays at `pki.schema.pkcs8.parse` — `encrypt`, `decrypt`, `export`, `import`, `generate`, `publicFromPrivate` |
package/lib/asn1-der.js CHANGED
@@ -660,6 +660,28 @@ function sequenceTlv(node) {
660
660
  return Buffer.concat([Buffer.from([TAGS.SEQUENCE | CONSTRUCTED_BIT]), encodeLength(content.length), content]);
661
661
  }
662
662
 
663
+ /** @internal A constructed value written into ONE allocation, rather than concatenating the children
664
+ * and then concatenating that with the header. The two-step form leaves an intermediate holding
665
+ * everything the children carry; where they carry private material that intermediate is a copy of it
666
+ * no caller can reach to clear, since it is a local here and becomes garbage on return. Its output is
667
+ * byte-identical to the two-step form: the same identifier, the same length, the same children in
668
+ * the same order. */
669
+ function encodeConstructed(classBits, tagNumber, parts) {
670
+ var total = 0;
671
+ for (var i = 0; i < parts.length; i++) total += parts[i].length;
672
+ var id = encodeIdentifier(classBits, true, tagNumber);
673
+ var len = encodeLength(total);
674
+ var out = intrinsic.bufferAlloc(id.length + len.length + total);
675
+ intrinsic.typedArraySet(out, id, 0);
676
+ intrinsic.typedArraySet(out, len, id.length);
677
+ var at = id.length + len.length;
678
+ for (var j = 0; j < parts.length; j++) {
679
+ intrinsic.typedArraySet(out, parts[j], at);
680
+ at += parts[j].length;
681
+ }
682
+ return out;
683
+ }
684
+
663
685
  function encodeIdentifier(classBits, constructed, tagNumber) {
664
686
  if (typeof tagNumber !== "number" || !isFinite(tagNumber) || tagNumber < 0 || Math.floor(tagNumber) !== tagNumber) {
665
687
  throw new Asn1Error("asn1/bad-tag", "tag number must be a non-negative integer");
@@ -853,16 +875,18 @@ var build = intrinsic.assign(intrinsic.create(null), {
853
875
  },
854
876
  utcTime: function (date) { return _universal(TAGS.UTC_TIME, false, Buffer.from(_utcTimeString(date), "latin1")); },
855
877
  generalizedTime: function (date) { return _universal(TAGS.GENERALIZED_TIME, false, Buffer.from(_generalizedTimeString(date), "latin1")); },
856
- sequence: function (children) { return _universal(TAGS.SEQUENCE, true, Buffer.concat(_asBufferArray(children, "build.sequence"))); },
878
+ sequence: function (children) {
879
+ return encodeConstructed(CLASS_UNIVERSAL, TAGS.SEQUENCE, _asBufferArray(children, "build.sequence"));
880
+ },
857
881
  set: function (children) {
858
882
  var arr = _asBufferArray(children, "build.set").slice();
859
883
  arr.sort(Buffer.compare);
860
- return _universal(TAGS.SET, true, Buffer.concat(arr));
884
+ return encodeConstructed(CLASS_UNIVERSAL, TAGS.SET, arr);
861
885
  },
862
886
  setOf: function (children) {
863
887
  var arr = _asBufferArray(children, "build.setOf").slice();
864
888
  arr.sort(Buffer.compare);
865
- return _universal(TAGS.SET, true, Buffer.concat(arr));
889
+ return encodeConstructed(CLASS_UNIVERSAL, TAGS.SET, arr);
866
890
  },
867
891
  explicit: function (tagNumber, inner) { return encodeTLV(CLASS_CONTEXT, true, tagNumber, _asBuffer(inner, "build.explicit")); },
868
892
  contextPrimitive: function (tagNumber, content) { return encodeTLV(CLASS_CONTEXT, false, tagNumber, _asBuffer(content, "build.contextPrimitive")); },
package/lib/constants.js CHANGED
@@ -115,6 +115,10 @@ var LIMITS = Object.assign(Object.create(null), {
115
115
  MAX_DECODE_DEPTH_CEILING: 256,
116
116
  PEM_MAX_BYTES: BYTES.mib(16),
117
117
  DER_MAX_INTEGER_BYTES: BYTES.kib(16),
118
+ DH_MAX_MODULUS_BYTES: 512,
119
+ DH_MIN_SUBGROUP_BYTES: 20,
120
+ DH_MIN_MODULUS_BYTES: 256,
121
+ DH_PRIME_MEMO_ENTRIES: 64,
118
122
  OID_MAX_SUBIDENTIFIER_BYTES: 32,
119
123
  HTTP_MAX_RESPONSE_BYTES: BYTES.mib(24),
120
124
  HTTP_AUTH_HEADER_MAX_BYTES: BYTES.kib(8),
package/lib/crmf-sign.js CHANGED
@@ -17,16 +17,29 @@
17
17
  * @card Build a CRMF CertReqMessages with a signature proof of possession.
18
18
  */
19
19
 
20
+ var nodeCrypto = require("node:crypto");
21
+ /** @internal Bound at module load, like every other capture here: the proof below decides what it
22
+ * agrees and what it hashes, so a replacement swapped in afterwards must not be able to steer it. */
23
+ var _createHash = nodeCrypto.createHash;
24
+ var _createHmac = nodeCrypto.createHmac;
25
+ var _diffieHellman = nodeCrypto.diffieHellman;
26
+ var _createPublicKey = nodeCrypto.createPublicKey;
27
+ var _createPrivateKey = nodeCrypto.createPrivateKey;
28
+ var _checkPrimeSync = nodeCrypto.checkPrimeSync;
20
29
  var asn1 = require("./asn1-der");
21
30
  var oid = require("./oid");
31
+ var x509 = require("./schema-x509");
22
32
  var crmf = require("./schema-crmf");
23
33
  var signScheme = require("./sign-scheme");
24
34
  var pkix = require("./schema-pkix");
35
+ var schema = require("./schema-engine");
25
36
  var pkiBuild = require("./pki-build");
26
37
  var frameworkError = require("./framework-error");
27
38
  var guard = require("./guard-all");
39
+ var constants = require("./constants");
28
40
  var intrinsic = require("./guard-intrinsic");
29
41
  var _hasOwn = intrinsic.hasOwn;
42
+ var _isBuffer = intrinsic.isBuffer;
30
43
  var _stringify = intrinsic.stringify;
31
44
  var cms = require("./schema-cms");
32
45
  var cmsEncrypt = require("./cms-encrypt");
@@ -56,7 +69,7 @@ var POP_KEYS_BY_ARM = intrinsic.assign(intrinsic.create(null), {
56
69
  type: 1, method: 1, privateKey: 1, identifier: 1, recipients: 1, archive: 1,
57
70
  contentEncryptionAlgorithm: 1,
58
71
  },
59
- agreeMAC: { type: 1, method: 1 },
72
+ agreeMAC: { type: 1, method: 1, key: 1, caCert: 1 },
60
73
  thisMessage: { type: 1, method: 1 },
61
74
  dhMAC: { type: 1, method: 1 },
62
75
  });
@@ -70,7 +83,7 @@ var REGINFO_VALUE = intrinsic.assign(intrinsic.create(null), { utf8Pairs: _ctlUt
70
83
 
71
84
 
72
85
  function _encodeOptionalValidity(validity) {
73
- if (!validity || typeof validity !== "object" || Buffer.isBuffer(validity)) throw _err("crmf/bad-validity", "validity must be an object { notBefore?, notAfter? }");
86
+ if (!validity || typeof validity !== "object" || _isBuffer(validity)) throw _err("crmf/bad-validity", "validity must be an object { notBefore?, notAfter? }");
74
87
  var nb = validity.notBefore, na = validity.notAfter;
75
88
  if (nb == null && na == null) throw _err("crmf/bad-validity", "validity must contain notBefore or notAfter (RFC 4211 sec. 5)");
76
89
  var parts = [];
@@ -81,7 +94,7 @@ function _encodeOptionalValidity(validity) {
81
94
  return b.implicit(4, b.sequence(parts));
82
95
  }
83
96
  function _encodeCertTemplate(tpl, opts) {
84
- if (!tpl || typeof tpl !== "object" || Buffer.isBuffer(tpl)) throw _err("crmf/bad-cert-template", "certTemplate must be an object");
97
+ if (!tpl || typeof tpl !== "object" || _isBuffer(tpl)) throw _err("crmf/bad-cert-template", "certTemplate must be an object");
85
98
  var allowed = (opts && opts.revocation) ? REVOCATION_TEMPLATE_KEYS : KNOWN_TEMPLATE_KEYS;
86
99
  guard.identifier.assertKnownKeys(tpl, allowed, _err, "crmf/bad-input", "unknown certTemplate field ");
87
100
  var fields = [];
@@ -157,7 +170,762 @@ function _encKeyWithID(privateKeyDer, identifier) {
157
170
  return b.sequence([b.raw(privateKeyDer), idNode]);
158
171
  }
159
172
 
160
- function _buildPopoPrivKey(pop, mode, template) {
173
+ /** @internal The digest each static Diffie-Hellman proof algorithm is defined over, keyed by the OID
174
+ * that names it. RFC 2875 sec. 4.4 registers one, `id-dhPop-static-HMAC-SHA1`, and its digest is part
175
+ * of what that OID means: the derivation and the MAC are SHA-1 because the identifier on the wire says
176
+ * so, not because this side chose it. A second algorithm would be a row here, as it is for the CMC
177
+ * challenge's own witness and MAC tables. */
178
+ var DH_POP_DIGEST = intrinsic.create(null);
179
+ DH_POP_DIGEST[O("id-dhPop-static-HMAC-SHA1")] = "sha1";
180
+
181
+ /** @internal The RFC 2875 sec. 3 static Diffie-Hellman proof of possession, which RFC 4211 sec. 4.3
182
+ * requires every DH implementation to support. The requester holds a certificate for the authority, and
183
+ * a key on the authority's own group; the secret they agree keys a MAC over the request, so producing
184
+ * it demonstrates possession of the private half without signing anything.
185
+ *
186
+ * The MAC covers the DER `certReq`, which the ASN.1 comment on POPOPrivKey states and the prose does
187
+ * not: "a MAC (over the DER-encoded value of the certReq parameter in CertReqMsg, which must include
188
+ * both subject and publicKey)". The `PKMACValue` field description names the DER-encoded public key
189
+ * instead, and that describes the OTHER place that structure is used, the `publicKeyMAC` of
190
+ * POPOSigningKeyInput. */
191
+ function _buildAgreeMac(pop, outerTag, certReqDer, template) {
192
+ /** @internal The POPOPrivKey comment states what the prose does not: the MAC covers a certReq "which
193
+ * must include both subject and publicKey". A request naming neither identifies nothing the proof
194
+ * could be about, so it is refused rather than MACed as it stands. */
195
+ if (!template || !template.complete) {
196
+ throw _err("crmf/bad-popo", "an agreeMAC proof of possession covers a certReq that must include both the subject and the publicKey (RFC 4211 sec. 4.3), and this template names only one of them");
197
+ }
198
+ if (pop.key == null) throw _err("crmf/bad-popo", "an agreeMAC proof of possession needs pop.key, the requester's Diffie-Hellman private key, to agree the secret with the authority (RFC 2875 sec. 3)");
199
+ if (pop.caCert == null) throw _err("crmf/bad-popo", "an agreeMAC proof of possession needs pop.caCert, the authority's certificate the requester already holds, for its Diffie-Hellman public key and its names (RFC 4211 sec. 4.3)");
200
+
201
+ var caCertDer;
202
+ try {
203
+ caCertDer = guard.bytes.snapshotSource(pkix.coerceToDer(pop.caCert, {
204
+ pemLabel: "CERTIFICATE", PemError: frameworkError.PemError, ErrorClass: CrmfError, prefix: "crmf",
205
+ }), CrmfError, "crmf/bad-popo", "the authority certificate");
206
+ } catch (e) {
207
+ if (e instanceof CrmfError && e.code === "crmf/bad-popo") throw e;
208
+ throw _err("crmf/bad-popo", "pop.caCert is not a certificate this runtime can read", e);
209
+ }
210
+ var parsedCa;
211
+ try { parsedCa = x509.parse(caCertDer); }
212
+ catch (e) { throw _err("crmf/bad-popo", "pop.caCert is not a well-formed certificate", e); }
213
+
214
+ /** @internal RFC 4211 sec. 4.3: "If either the subject or issuer name in the CA certificate is empty,
215
+ * then the alternative name should be used in its place." An empty name with no alternative leaves the
216
+ * derivation with nothing to bind, so it is refused rather than derived from an empty string.
217
+ * Only the subject half is reachable: RFC 5280 sec. 4.1.2.4 requires a non-empty issuer, and the
218
+ * certificate parser pop.caCert passes through enforces it with x509/bad-issuer, so an authority
219
+ * certificate carrying an empty issuer never reaches this derivation. */
220
+ var leading = _nameOrAlternative(parsedCa, "subject", "subjectAltName");
221
+ var trailing = _nameOrAlternative(parsedCa, "issuer", "issuerAltName");
222
+
223
+ /** @internal RFC 5280 sec. 4.2.1.3: a keyUsage extension restricts the certified key to the
224
+ * purposes it asserts, and this proof uses the authority's key to agree a secret. A certificate
225
+ * that states its purposes and does not state this one is refused rather than used for it. A
226
+ * certificate carrying no keyUsage asserts no restriction and is left alone. */
227
+ var caKu = pkix.keyUsageOf(NS, parsedCa, _err, "crmf/bad-popo", "authority certificate's");
228
+ if (caKu && caKu.keyAgreement !== true) {
229
+ throw _err("crmf/bad-popo", "the authority certificate's keyUsage does not assert keyAgreement, so its key is not certified for the agreement this proof performs (RFC 5280 sec. 4.2.1.3)");
230
+ }
231
+
232
+ var caPub, eePriv;
233
+ /** @internal A finite-field key reaches a certificate in two encodings, and the group is checked
234
+ * whichever one carried it. The X9.42 form is rewritten into the form this runtime classifies, and
235
+ * that rewrite checks the group on the way; the PKCS#3 form needs no rewrite, so it is checked
236
+ * here instead of arriving unexamined because it happened to need no conversion. */
237
+ var caX942 = _x942ToPkcs3(parsedCa.subjectPublicKeyInfo.bytes, "the authority certificate's");
238
+ var caSpkiBytes;
239
+ if (caX942 !== null) {
240
+ _assertDhGroup(caX942.p, caX942.g, caX942.y, caX942.q, caX942.j, true, "the authority certificate's");
241
+ _assertAgreementExponent(caX942, "the authority certificate's key");
242
+ caSpkiBytes = caX942.der;
243
+ } else {
244
+ caSpkiBytes = parsedCa.subjectPublicKeyInfo.bytes;
245
+ var pkcs3 = _pkcs3Params(caSpkiBytes, "the authority certificate's");
246
+ if (pkcs3 !== null) {
247
+ _assertDhGroup(pkcs3.p, pkcs3.g, pkcs3.y, null, null, true, "the authority certificate's");
248
+ _assertAgreementExponent(pkcs3, "the authority certificate's key");
249
+ }
250
+ }
251
+ try { caPub = _createPublicKey({ key: caSpkiBytes, format: "der", type: "spki" }); }
252
+ catch (e) { throw _err("crmf/bad-popo", "the authority certificate does not carry a key this runtime can agree with", e); }
253
+ /** @internal The snapshot of the caller's key is this function's own copy of private material, so it
254
+ * is registered for the wipe below rather than left to the argument boundary, which clears what it
255
+ * was handed and not what this made from it. */
256
+ var keySnapshot = null;
257
+ var translated = null;
258
+ var zz = null, k = null;
259
+ try {
260
+ /** @internal Inside the cleanup scope, because the import can throw AFTER the snapshot exists: a
261
+ * catch that returned from out here would leave that copy of private material behind. */
262
+ try {
263
+ if (pop.key && typeof pop.key === "object" && pop.key.asymmetricKeyType != null) {
264
+ eePriv = pop.key;
265
+ } else if (pop.key && typeof pop.key === "object" && pop.key.type === "private" &&
266
+ typeof pop.key.export === "function") {
267
+ /** @internal A key object the runtime holds without classifying, which is what it makes of an
268
+ * X9.42 key. It reads its own encoding back, so the same rewrite the serialized forms take
269
+ * applies here: supporting the encoding for a caller holding bytes and refusing the caller
270
+ * holding the key those bytes import to would be the same key admitted one way. The export
271
+ * is this function's own copy of private material and is cleared with the rest. */
272
+ keySnapshot = pop.key.export({ format: "der", type: "pkcs8" });
273
+ translated = _x942PrivToPkcs3(keySnapshot);
274
+ eePriv = translated !== null
275
+ ? _createPrivateKey({ key: translated, format: "der", type: "pkcs8" })
276
+ : pop.key;
277
+ } else if (guard.bytes.isByteSource(pop.key)) {
278
+ keySnapshot = guard.bytes.snapshotSource(pop.key, CrmfError, "crmf/bad-popo", "the requester's private key");
279
+ /** @internal Assigned to the outer name, not a local one: the rewrite is this function's own
280
+ * copy of the private value, and an import that throws after it exists must not leave it
281
+ * behind. The wipe below clears whatever was made, on every way out. */
282
+ translated = _x942PrivToPkcs3(keySnapshot);
283
+ eePriv = _createPrivateKey({ key: translated || keySnapshot, format: "der", type: "pkcs8" });
284
+ } else {
285
+ /** @internal A PEM key reaches the same conversion: it is the same key in the same encoding
286
+ * with an armor around it, so admitting one form and not the other would support X9.42 for a
287
+ * caller holding DER and refuse the caller holding the identical bytes in PEM. */
288
+ var pemDer = _pemPrivateKeyDer(pop.key);
289
+ if (pemDer !== null) {
290
+ keySnapshot = pemDer;
291
+ translated = _x942PrivToPkcs3(keySnapshot);
292
+ eePriv = _createPrivateKey({ key: translated || keySnapshot, format: "der", type: "pkcs8" });
293
+ } else {
294
+ eePriv = _createPrivateKey(pop.key);
295
+ }
296
+ }
297
+ } catch (e) {
298
+ if (e instanceof CrmfError) throw e;
299
+ throw _err("crmf/bad-popo", "pop.key is not a private key this runtime can read", e);
300
+ }
301
+ /** @internal The proof is about the key being certified, so the key that agrees the secret has to
302
+ * be the private half of the one the template asks for. The authority derives its side from the
303
+ * template's public key, so a private key from another pair agrees a secret with the authority
304
+ * perfectly well and produces a MAC the authority cannot reproduce: a proof of possession of
305
+ * something this request never asked to have certified. The encryptedKey arm holds its enclosed
306
+ * key to the same rule. */
307
+ var eeSpki;
308
+ try { eeSpki = _createPublicKey(eePriv).export({ format: "der", type: "spki" }); }
309
+ catch (e) { throw _err("crmf/bad-popo", "the public half of pop.key could not be derived to check it against the requested key", e); }
310
+ /** @internal Compared as keys, not as bytes. A PKCS#3 DHParameter carries an optional
311
+ * privateValueLength, so one finite-field key has more than one valid SubjectPublicKeyInfo and a
312
+ * byte comparison refuses a request that names the very key it was made with. */
313
+ /** @internal The requested key is read in both encodings too. A template naming the key in the
314
+ * X9.42 form and a pop.key holding its PKCS#3 private half are the same key, and comparing the
315
+ * two encodings through the runtime answers false, so the template is brought to the one form
316
+ * before the comparison. Its own subgroup is checked on the way, as the authority's is. */
317
+ /** @internal The requested key is read in both encodings on the same footing. The X9.42 form is
318
+ * brought to the one the runtime classifies, and the PKCS#3 form is read in place so the shape
319
+ * this comparison rests on is checked either way: the request carries the caller's own encoding,
320
+ * so a malformed one it never read would travel under a MAC covering it. */
321
+ /** @internal The requested key is brought to the one encoding so the comparison is about keys,
322
+ * and its shape is read either way. Its p and g are the authority's, which the runtime requires
323
+ * this key to share and which the agreement's own floors already answered for; its q and j are
324
+ * not, since the caller states those here and the conversion drops them. They are held to the
325
+ * key they describe, so the request cannot carry a subgroup order its own key does not have. */
326
+ var templateSpki = template.spki;
327
+ if (templateSpki) {
328
+ var converted = _x942ToPkcs3(templateSpki, "certTemplate.publicKey's");
329
+ if (converted !== null) {
330
+ _assertDhGroup(converted.p, converted.g, converted.y, converted.q, converted.j, false, "certTemplate.publicKey's");
331
+ templateSpki = converted.der;
332
+ } else {
333
+ var tPkcs3 = _pkcs3Params(templateSpki, "certTemplate.publicKey's");
334
+ if (tPkcs3 !== null) _assertDhGroup(tPkcs3.p, tPkcs3.g, tPkcs3.y, null, null, false, "certTemplate.publicKey's");
335
+ }
336
+ }
337
+ if (!templateSpki || !_b.samePublicKey(eeSpki, templateSpki)) {
338
+ throw _err("crmf/bad-popo", "pop.key is not the private half of certTemplate.publicKey; the authority derives its side of the agreement from the requested key, so a proof made with any other key demonstrates possession of something this request does not ask to have certified (RFC 4211 sec. 4.3)");
339
+ }
340
+ /** @internal The exponent this key agrees with has to be one the authority cannot work out.
341
+ * RFC 2631 sec. 2.2 states X9.42's own requirement: "X9.42 requires that the private key x be in
342
+ * the interval [2, (q - 2)]." The three exponents outside it agree a secret that follows from the
343
+ * authority's certificate alone: x = 0 agrees one, x = 1 agrees the authority's public value
344
+ * itself, and x = q-1 agrees the inverse of that value. A MAC keyed from any of them demonstrates
345
+ * possession of nothing, since whoever holds the certificate can compute the same key.
346
+ * The exponent is read off the public value rather than out of the key: g^x is 1, g and g inverse
347
+ * exactly at those three, so the test needs no copy of private material and no stated order.
348
+ * After the comparison above, which the requested key reached only through the size bound its own
349
+ * parameters were held to, so the inversion below runs on a modulus that was measured first. */
350
+ _assertAgreementExponent(_pkcs3Params(eeSpki, "pop.key's"), "pop.key");
351
+ /** @internal Finite-field Diffie-Hellman only. RFC 2875 sec. 3 defines this algorithm over a group
352
+ * with parameters g and p, agreeing `g^xy mod p`. An elliptic-curve or montgomery pair agrees a
353
+ * secret through the same call and would be emitted under the same OID, which names an operation
354
+ * the recipient would not be performing. */
355
+ if (eePriv.asymmetricKeyType !== "dh" || caPub.asymmetricKeyType !== "dh") {
356
+ /** @internal A key this runtime imported but did not classify reports no asymmetricKeyType, which
357
+ * is what an X9.42 dhpublicnumber SubjectPublicKeyInfo does here where the PKCS#3 dhKeyAgreement
358
+ * form is classified. The agreement refuses such a key on its own, so naming the unrecognized
359
+ * side is the whole of the difference between the two messages. */
360
+ throw _err("crmf/bad-popo", "the static Diffie-Hellman proof of possession is defined over a finite-field group (RFC 2875 sec. 3), and " +
361
+ _keyTypeLabel("pop.key", eePriv) + " against " + _keyTypeLabel("the authority certificate's key", caPub));
362
+ }
363
+ /** @internal The agreement's own Buffer, not a copy of it: wrapping it would leave the original
364
+ * holding the secret with nothing to clear it. */
365
+ try { zz = _diffieHellman({ privateKey: eePriv, publicKey: caPub }); }
366
+ catch (e) { throw _err("crmf/bad-popo", "the requester's key and the authority's key did not agree a secret; this proof needs a key on the authority's own parameters (RFC 4211 sec. 4.3)", e); }
367
+ /** @internal K = SHA1(LeadingInfo | ZZ | TrailingInfo) (RFC 2875 sec. 3, step 3c), under the
368
+ * digest the proof's own algorithm identifier names. */
369
+ var popAlgOid = O("id-dhPop-static-HMAC-SHA1");
370
+ var digest = DH_POP_DIGEST[popAlgOid];
371
+ k = _createHash(digest).update(leading).update(zz).update(trailing).digest();
372
+ /** @internal Ordinary HMAC-SHA1. RFC 2875 sec. 3(d) writes the construction correctly and then
373
+ * labels its pads the wrong way round, calling 0x36 the outer pad and 0x5C the inner one, which is
374
+ * the reverse of RFC 2104; the same sentence says the MAC is computed "as per [RFC2104]". */
375
+ var mac = _createHmac(digest, k).update(certReqDer).digest();
376
+ /** @internal The BIT STRING carries the DhPopStatic SEQUENCE, not the raw MAC. RFC 2875 sec. 3
377
+ * says so after the computation: "DhPopStatic is encoded as a BIT STRING and is the signature
378
+ * value (i.e. encodes the above sequence instead of the raw output from 3d)". `issuerAndSerial`
379
+ * names the certificate the public key came from, and is "omitted if the public key did not come
380
+ * from a certificate"; here it always does, since the caller supplies it. */
381
+ var dhPopStatic = b.sequence([
382
+ b.sequence([b.raw(parsedCa.issuer.bytes), b.integer(parsedCa.serialNumber)]),
383
+ b.octetString(mac),
384
+ ]);
385
+ return b.explicit(outerTag, b.implicit(3, b.sequence([
386
+ b.sequence([b.oid(popAlgOid)]),
387
+ b.bitString(dhPopStatic, 0),
388
+ ])));
389
+ } finally {
390
+ var made = [];
391
+ if (zz) guard.list.append(made, zz);
392
+ if (k) guard.list.append(made, k);
393
+ if (keySnapshot) guard.list.append(made, keySnapshot);
394
+ if (translated) guard.list.append(made, translated);
395
+ if (made.length) guard.secret.zeroizeAll(made, CrmfError, "crmf/bad-popo", "the agreed proof-of-possession secret");
396
+ }
397
+ }
398
+
399
+ /** @internal The distinguished name a derivation binds to, or the alternative name when the certificate
400
+ * leaves it empty (RFC 4211 sec. 4.3). A certificate carrying neither cannot key this proof. */
401
+ /** @internal The group and the public value a certificate states, checked once for both encodings a
402
+ * finite-field key is written in. q is the subgroup order where the encoding states one and null
403
+ * where it does not, which is the whole difference between the X9.42 and PKCS#3 forms.
404
+ *
405
+ * The sizes come first because every test after them raises one operand to the power of another and
406
+ * proves a modulus prime, and the DER reader admits an INTEGER far wider than any group. The bound
407
+ * is 4096 bits, which covers every MODP group a certificate carries; proving a modulus of that width
408
+ * prime costs about a second, and the width the reader would otherwise allow costs tens of seconds.
409
+ *
410
+ * y is bounded to the group whichever encoding carried it. A value of 1 or p-1 has order 1 or 2, so
411
+ * the secret it agrees exposes the requester's private exponent modulo that order; those are the
412
+ * only small orders a safe prime has, which is what the range test alone answers for. Where q is
413
+ * stated the subgroup test answers for the rest, and it means something only because q is proven
414
+ * prime: y^q = 1 otherwise bounds the order of y to a divisor of q rather than to q. */
415
+ /** @internal Whether a public value in this agreement states an exponent the other side could work
416
+ * out. Both halves are held to it: an agreement has two exponents and either one outside the interval
417
+ * makes the secret public, so a rule stated for the requester alone would leave the authority free to
418
+ * carry the same key. Takes the PKCS#3 parameters of a key that agrees, or null when the key is not a
419
+ * finite-field one, in which case there is no exponent of this kind to test.
420
+ * The inverse of g is computed as g^(p-2), which is the inverse when p is prime. Each caller runs the
421
+ * group's own checks first, so p is proven prime and bounded before this exponentiates with it.
422
+ * The excluded values are the ones whose secret follows with NO search: an exponent of 0, 1 or -1
423
+ * agrees one, the other side's public value, and its inverse. A safe prime also has elements of
424
+ * order 2q, and the PKCS#3 form states no order, so such a generator is admitted and its square root
425
+ * of one, p-1, reflects each of those values: the exponent q+1 produces p-g and q-1 produces p minus
426
+ * the inverse of g, and each agrees the negation of a secret that already follows. The reflections
427
+ * are excluded with the values they reflect, since reading the two alone would hold a group with a
428
+ * full-order generator to half the rule.
429
+ * What is excluded is the set the GROUP determines: five values, fixed by p and g, that an exponent
430
+ * lands on without anybody choosing it. An exponent a reader could instead GUESS, whether small like
431
+ * 2 or structured like (q+1)/2, is a different matter and is not tested here. Recognizing one means
432
+ * raising g to that candidate and comparing, so refusing a family of them is a search with a bound,
433
+ * and any bound this picked would refuse keys RFC 2631 sec. 2.2 admits while a reader used the next
434
+ * candidate past it. Whether an exponent is unpredictable is a property of how the key was
435
+ * generated, which no specification asks a request builder to verify and which the public value does
436
+ * not carry. */
437
+ function _assertAgreementExponent(parts, what) {
438
+ if (parts === null) return;
439
+ var gInv = _modPow(parts.g, parts.p - 2n, parts.p);
440
+ if (parts.y === 1n || parts.y === parts.g || parts.y === gInv ||
441
+ parts.y === parts.p - parts.g || parts.y === parts.p - gInv) {
442
+ throw _err("crmf/bad-popo", what + " states a private exponent outside the interval [2, q-2] that X9.42 " +
443
+ "requires (RFC 2631 sec. 2.2), so the secret agreed with it follows from values the request and the " +
444
+ "authority certificate already carry, and the proof would demonstrate possession of nothing");
445
+ }
446
+ }
447
+
448
+ /** @internal Whether a stated order and cofactor describe the p and g stated beside them. These are
449
+ * the tests that answer that question with a comparison, a multiplication and a modulo, so their cost
450
+ * grows gently with the modulus and every path that reads these parameters can afford them: the
451
+ * archival arm reads a key without bounding its size, and the tests it leaves to the certifying
452
+ * authority are the ones whose cost grows with it, a modular exponentiation and two primality proofs.
453
+ * A cofactor states (p-1)/q, so a cofactor with no order beside it states nothing. */
454
+ function _assertDhParamsCoherent(p, g, q, j, what) {
455
+ if (p <= 2n || g <= 1n || g >= p - 1n) {
456
+ throw _err("crmf/bad-popo", what + " parameters are not a Diffie-Hellman group");
457
+ }
458
+ if (j !== null && (q === null || j * q !== p - 1n)) {
459
+ throw _err("crmf/bad-popo", what + " X9.42 cofactor does not match its own p and q");
460
+ }
461
+ if (q !== null && (q <= 1n || (p - 1n) % q !== 0n)) {
462
+ throw _err("crmf/bad-popo", what + " X9.42 domain parameters state a subgroup order its own p and g do not have");
463
+ }
464
+ }
465
+
466
+ function _assertDhGroup(p, g, y, q, j, forAgreement, what) {
467
+ if (p >= _DH_MAX || g >= _DH_MAX || (y !== null && y >= _DH_MAX) ||
468
+ (q !== null && q >= _DH_MAX) || (j !== null && j >= _DH_MAX)) {
469
+ throw _err("crmf/bad-popo", what + " parameters are larger than any Diffie-Hellman group this toolkit agrees over (" +
470
+ constants.LIMITS.DH_MAX_MODULUS_BYTES + " bytes)");
471
+ }
472
+ _assertDhParamsCoherent(p, g, q, j, what);
473
+ /** @internal A PrivateKeyInfo states the group without stating a public value in it, so the two
474
+ * tests that hold a value to these parameters have nothing to run against and the rest still do.
475
+ * The private half's own p and g are the ones its public half is compared against, and that public
476
+ * half is held to the subgroup where it is read. */
477
+ if (y !== null && (y <= 1n || y >= p - 1n)) {
478
+ throw _err("crmf/bad-popo", what + " Diffie-Hellman public value is outside the group (RFC 2875 sec. 3)");
479
+ }
480
+ /** @internal A stated order is held against g before anything is proven prime. Both tests below
481
+ * cost seconds on a large modulus and this one costs a modular exponentiation, so a set of
482
+ * parameters that cannot be a group is turned away at the cheaper of the two. The rest of that
483
+ * question was already answered above, without exponentiating. */
484
+ if (q !== null && _modPow(g, q, p) !== 1n) {
485
+ throw _err("crmf/bad-popo", what + " X9.42 domain parameters state a subgroup order its own p and g do not have");
486
+ }
487
+ if (!_isPrime(p)) {
488
+ throw _err("crmf/bad-popo", what + " Diffie-Hellman modulus is not prime, so the group its parameters describe does not exist");
489
+ }
490
+ /** @internal With no stated subgroup order there is nothing to test y against, so the group itself
491
+ * has to be one whose only small orders the range above already excluded. That is a safe prime:
492
+ * p = 2r+1 with r prime has element orders 1, 2, r and 2r alone, and y = 1 and y = p-1 are the only
493
+ * values of the first two. A prime p is not enough on its own, since p-1 may carry small factors
494
+ * and then an order-3 value sits inside the range and the secret it agrees exposes the requester's
495
+ * private exponent modulo 3. */
496
+ var order;
497
+ if (q === null) {
498
+ /** @internal Nothing was stated, so there is nothing to hold the parameters to; only a key this
499
+ * proof will agree in has to be a group whose orders the range above already bounded. */
500
+ if (!forAgreement) return;
501
+ order = (p - 1n) / 2n;
502
+ if (!_isPrime(order)) {
503
+ throw _err("crmf/bad-popo", what + " parameters state no subgroup order and its modulus is not a safe prime, so nothing bounds the order of its public value (RFC 2875 sec. 3)");
504
+ }
505
+ } else {
506
+ if (!_isPrime(q)) {
507
+ throw _err("crmf/bad-popo", what + " X9.42 domain parameters state a subgroup order that is not prime, so a public value in it need not have that order");
508
+ }
509
+ order = q;
510
+ /** @internal The public value has to lie in the subgroup the parameters name. This is what the
511
+ * stated order says about the key, so it is checked wherever the parameters are read and not
512
+ * only where a secret is agreed: a request carries these parameters to whoever reads it next. */
513
+ if (y !== null && _modPow(y, q, p) !== 1n) {
514
+ throw _err("crmf/bad-popo", what + " Diffie-Hellman public value is not in the subgroup its own domain parameters state, so agreeing with it would expose the private exponent of whichever side agrees");
515
+ }
516
+ }
517
+ /** @internal Everything above answers whether the parameters describe the key they carry, which is
518
+ * asked of any key this reads. What follows is the strength the AGREEMENT needs, and a key being
519
+ * archived rather than agreed with is not held to it. */
520
+ if (!forAgreement) return;
521
+ /** @internal Whichever way the encoding stated it, the order has to be large. Proving it prime
522
+ * makes the order of y exactly that value rather than a divisor of it, which is worth nothing when
523
+ * the value itself is small: 3 is prime and divides p-1 for a great many p, and 7 is a safe prime
524
+ * whose own subgroup has order 3. Either way the secret exposes the requester's private exponent
525
+ * modulo a number small enough to search. The floor is the smallest subgroup order NIST SP 800-56A
526
+ * states for a finite-field group, so every real one clears it. */
527
+ if (order < _DH_MIN_Q) {
528
+ throw _err("crmf/bad-popo", what + " parameters state a subgroup too small to hide a private exponent (under " +
529
+ constants.LIMITS.DH_MIN_SUBGROUP_BYTES + " bytes)");
530
+ }
531
+ /** @internal A large subgroup says the public value is hard to take a discrete log of INSIDE the
532
+ * group; it says nothing about the group itself, which index calculus attacks through the modulus.
533
+ * A 512-bit safe prime has a 255-bit subgroup and clears the floor above while the secret agreed
534
+ * in it is recoverable. The floor is the one the toolkit's own linter names for a public key. */
535
+ if (p < _DH_MIN_P) {
536
+ throw _err("crmf/bad-popo", what + " Diffie-Hellman modulus is under " +
537
+ constants.LIMITS.DH_MIN_MODULUS_BYTES + " bytes, which is too small to agree a secret in");
538
+ }
539
+ }
540
+
541
+ /** @internal The DER inside a PEM PRIVATE KEY block, or null when the value is not one. A caller
542
+ * holding a key in PEM holds the same bytes under an armor, so the conversion below has to see it. */
543
+ function _pemPrivateKeyDer(value) {
544
+ if (typeof value !== "string") return null;
545
+ /** @internal The decoder's own buffer is returned rather than a copy of it. Copying would leave
546
+ * the original holding the private key with nothing registered to clear it, which is the shape
547
+ * that puts a second copy of a secret beyond the reach of the wipe. */
548
+ try {
549
+ return pkix.pemDecode(value, "PRIVATE KEY", frameworkError.PemError);
550
+ } catch (_e) { return null; } // allow:swallow-unverified a value that is not a PEM private key is left to the import below to refuse
551
+ }
552
+
553
+ /** @internal A PKCS#8 private key in the X9.42 form, rewritten into the PKCS#3 one this runtime
554
+ * classifies, or null when it is not in that form. PrivateKeyInfo is SEQUENCE { version,
555
+ * privateKeyAlgorithm, privateKey OCTET STRING, attributes [0] OPTIONAL } (RFC 5958), and only the
556
+ * algorithm changes: the private value the OCTET STRING wraps is the same INTEGER either way. The
557
+ * public halves of this key are already read in both encodings, so leaving the private half in one
558
+ * of them would support the encoding for a requester holding somebody else's key and not their own. */
559
+ function _x942PrivToPkcs3(pkcs8Bytes) {
560
+ var node;
561
+ try { node = asn1.decode(pkcs8Bytes); } catch (_e) { return null; } // allow:swallow-unverified a key the runtime cannot read is refused by the import this stands before
562
+ if (!_isUniversal(node, 16) || !node.children || node.children.length < 3) return null;
563
+ var alg = node.children[1];
564
+ if (!_isUniversal(alg, 16) || !alg.children || alg.children.length !== 2) return null;
565
+ var algOid;
566
+ try { algOid = asn1.read.oid(alg.children[0]); } catch (_e2) { return null; } // allow:swallow-unverified an algorithm field with no OID is refused by that same import
567
+ if (algOid !== O("dhpublicnumber")) return null;
568
+ var dom;
569
+ try {
570
+ dom = _x942Domain(alg.children[1], "pop.key's");
571
+ } catch (e) {
572
+ if (e instanceof CrmfError) throw e;
573
+ throw _err("crmf/bad-popo", "pop.key states X9.42 domain parameters that could not be read", e);
574
+ }
575
+ /** @internal The order and cofactor this key states are held to the p and g it states them about,
576
+ * for the same reason the requested key's are: the PKCS#3 form carries neither, so this conversion
577
+ * is the last place either is looked at. The floors the agreement needs are not applied twice. This
578
+ * key's p and g are the requested key's, which the comparison below requires it to share and which
579
+ * the agreement already answered for. */
580
+ _assertDhGroup(dom.p, dom.g, null, dom.q, dom.j, false, "pop.key's");
581
+ var fields = [b.raw(node.children[0].bytes),
582
+ b.sequence([b.oid(O("dhKeyAgreement")), b.sequence([b.integer(dom.p), b.integer(dom.g)])]),
583
+ b.raw(node.children[2].bytes)];
584
+ for (var i = 3; i < node.children.length; i++) guard.list.append(fields, b.raw(node.children[i].bytes));
585
+ /** @internal The builder's own buffer, not a copy of it: a copy would leave the rewritten private
586
+ * key behind with nothing registered to clear it. */
587
+ return b.sequence(fields);
588
+ }
589
+
590
+ /** @internal The algorithm and the two fields a SubjectPublicKeyInfo is made of, or null when the
591
+ * bytes are not one. Both finite-field encodings read the same outer shape, so they read it here
592
+ * rather than each carrying a copy of the checks the other already made. */
593
+ function _spkiParts(spkiBytes) {
594
+ var node;
595
+ try { node = asn1.decode(spkiBytes); } catch (_e) { return null; } // allow:swallow-unverified both callers hand this DER a reader has already decoded once
596
+ if (!_isUniversal(node, 16) || !node.children || node.children.length !== 2) return null;
597
+ var alg = node.children[0];
598
+ if (!_isUniversal(alg, 16) || !alg.children || alg.children.length !== 2) return null;
599
+ var algOid;
600
+ try { algOid = asn1.read.oid(alg.children[0]); } catch (_e2) { return null; } // allow:swallow-unverified the reader the caller's key passes first refuses an algorithm field with no OID
601
+ return { node: node, algOid: algOid, params: alg.children[1] };
602
+ }
603
+
604
+ /** @internal The p, g and public value of a PKCS#3 dhKeyAgreement SubjectPublicKeyInfo, or null when
605
+ * the key is not in that form. DHParameter is SEQUENCE { prime, base, privateValueLength OPTIONAL }
606
+ * (PKCS#3 sec. 9), and it states no subgroup order, so the group it describes is checked without one. */
607
+ function _pkcs3Params(spkiBytes, what) {
608
+ var parts = _spkiParts(spkiBytes);
609
+ if (parts === null || parts.algOid !== O("dhKeyAgreement")) return null;
610
+ var node = parts.node;
611
+ try {
612
+ var prm = asn1.decode(parts.params.bytes);
613
+ if (!_isUniversal(prm, 16) || !prm.children || prm.children.length < 2 || prm.children.length > 3) {
614
+ throw _err("crmf/bad-popo", what + " PKCS#3 Diffie-Hellman parameters are not a DHParameter SEQUENCE");
615
+ }
616
+ var p = asn1.read.integer(prm.children[0]);
617
+ /** @internal privateValueLength is the one optional field DHParameter carries, and it is an
618
+ * INTEGER. A third field of any other type is not that field, and this reader is the only thing
619
+ * that looks at these bytes before the request travels under a MAC covering them. */
620
+ if (prm.children.length === 3) {
621
+ if (!_isUniversal(prm.children[2], 2)) {
622
+ throw _err("crmf/bad-popo", what + " PKCS#3 privateValueLength is not an INTEGER");
623
+ }
624
+ /** @internal Read, not counted. An INTEGER carries at least one content octet, so a field
625
+ * tagged as one and holding none is not a length, and this reader is the only thing that looks
626
+ * at these bytes before the request travels under a MAC covering them. */
627
+ var pvl = asn1.read.integer(prm.children[2]);
628
+ if (pvl <= 0n) {
629
+ throw _err("crmf/bad-popo", what + " PKCS#3 privateValueLength is not a positive length");
630
+ }
631
+ /** @internal The field states how many bits the private value has, and a private value is less
632
+ * than the modulus, so a length above the modulus's own bit count describes no value the group
633
+ * holds. The encoded size bounds the count before anything is shifted by it, because this
634
+ * reader also serves an arm that reads a key without bounding its modulus and the field itself
635
+ * is an INTEGER the codec admits at any width. */
636
+ if (pvl > intrinsic.BigInt(prm.children[0].bytes.length) * 8n || (1n << (pvl - 1n)) > p) {
637
+ throw _err("crmf/bad-popo", what + " PKCS#3 privateValueLength states a private value longer than its own modulus, which no value in the group is");
638
+ }
639
+ }
640
+ var pub = asn1.read.bitString(node.children[1]);
641
+ if (!guard.crypto.isOctetAligned(pub)) {
642
+ throw _err("crmf/bad-popo", what + " Diffie-Hellman public key BIT STRING must be octet-aligned (0 unused bits)");
643
+ }
644
+ return { p: p, g: asn1.read.integer(prm.children[1]), y: asn1.read.integer(asn1.decode(pub.bytes)) };
645
+ } catch (e) {
646
+ if (e instanceof CrmfError) throw e;
647
+ throw _err("crmf/bad-popo", what + " PKCS#3 Diffie-Hellman key could not be read", e);
648
+ }
649
+ }
650
+
651
+ /** @internal A container is read for the tag it carries and not for merely having children: a
652
+ * context-specific constructed value holds children too, and converting one would rewrite a key the
653
+ * recipient's own reader refuses into a PKCS#3 key that imports, so the request would carry a public
654
+ * key nothing else can read. The predicate itself is the engine's. */
655
+ var _isUniversal = schema.isUniversal;
656
+
657
+ /** @internal ValidationParms is SEQUENCE { seed BIT STRING, pgenCounter INTEGER } (RFC 3279
658
+ * sec. 2.3.3). The conversion drops it, so reading it is the only thing that answers for it: a
659
+ * certificate whose parameters do not hold the two fields is malformed rather than merely carrying
660
+ * something this does not need. */
661
+ function _assertValidationParms(node, what) {
662
+ var kids = node.children;
663
+ if (!_isUniversal(node, 16) || !kids || kids.length !== 2 ||
664
+ !_isUniversal(kids[0], 3) || !_isUniversal(kids[1], 2)) {
665
+ throw _err("crmf/bad-popo", what + " X9.42 validationParms is not a seed BIT STRING with a pgenCounter INTEGER");
666
+ }
667
+ asn1.read.bitString(kids[0]);
668
+ asn1.read.integer(kids[1]);
669
+ }
670
+
671
+ /** @internal The p, g, q and cofactor an X9.42 DomainParameters states. DomainParameters is
672
+ * SEQUENCE { p, g, q, j OPTIONAL, validationParms OPTIONAL } (RFC 3279 sec. 2.3.3), and the PKCS#3
673
+ * form this runtime classifies carries none of the last three, so every field is read HERE, before
674
+ * the parameter that states it is dropped. Both halves of a finite-field key carry this structure and
675
+ * both take that conversion, so both read it in this one place: a field read on one side and skipped
676
+ * on the other is a key the runtime refuses in the encoding it was handed and this rewrites into one
677
+ * it accepts. The algorithm named dhpublicnumber, so these bytes are DomainParameters or the key is
678
+ * malformed; there is no third reading that would let a shape this does not recognize travel on. */
679
+ function _x942Domain(paramsNode, what) {
680
+ var domain = asn1.decode(paramsNode.bytes);
681
+ if (!_isUniversal(domain, 16) || !domain.children ||
682
+ domain.children.length < 3 || domain.children.length > 5) {
683
+ throw _err("crmf/bad-popo", what + " X9.42 domain parameters are not a DomainParameters SEQUENCE of p, g and q with at most two optional fields after them");
684
+ }
685
+ var out = {
686
+ p: asn1.read.integer(domain.children[0]),
687
+ g: asn1.read.integer(domain.children[1]),
688
+ q: asn1.read.integer(domain.children[2]),
689
+ j: null,
690
+ };
691
+ /** @internal j and validationParms are independently optional, so a fourth field is told apart by
692
+ * its tag rather than by its position: an INTEGER is the cofactor and a SEQUENCE is the validation
693
+ * parameters, which may appear with no cofactor before them. */
694
+ if (domain.children.length >= 4) {
695
+ var opt = domain.children[3];
696
+ if (_isUniversal(opt, 2)) {
697
+ out.j = asn1.read.integer(opt);
698
+ if (domain.children.length === 5) _assertValidationParms(domain.children[4], what);
699
+ } else if (_isUniversal(opt, 16)) {
700
+ if (domain.children.length === 5) {
701
+ throw _err("crmf/bad-popo", what + " X9.42 domain parameters carry a field after validationParms");
702
+ }
703
+ _assertValidationParms(opt, what);
704
+ } else {
705
+ throw _err("crmf/bad-popo", what + " X9.42 domain parameters carry a fourth field that is neither a cofactor nor validationParms");
706
+ }
707
+ }
708
+ return out;
709
+ }
710
+
711
+ /** @internal One past the largest Diffie-Hellman operand this module computes with, built once. */
712
+ /** @internal Two raised to a count of BITS, so a bound states the width it is named for: a value is
713
+ * at least n bits wide exactly when it is not below 2^(n-1), and at most n bits wide exactly when it
714
+ * is below 2^n. Counting in bytes and shifting by eight per byte lands a whole byte short of that. */
715
+ function _pow2(bits) {
716
+ var v = 1n;
717
+ for (var i = 0; i < bits; i++) v <<= 1n;
718
+ return v;
719
+ }
720
+
721
+ var _DH_MAX = _pow2(8 * constants.LIMITS.DH_MAX_MODULUS_BYTES);
722
+
723
+ /** @internal The smallest modulus a group may be agreed in, and the smallest order a q may name. */
724
+ var _DH_MIN_P = _pow2(8 * constants.LIMITS.DH_MIN_MODULUS_BYTES - 1);
725
+ var _DH_MIN_Q = _pow2(8 * constants.LIMITS.DH_MIN_SUBGROUP_BYTES - 1);
726
+
727
+ /** @internal Whether a value is prime, remembered across calls. Proving a 4096-bit modulus prime
728
+ * costs seconds, and an enrollment run asks the same question of the same group every time: the
729
+ * authority's parameters do not change between requests, and the requester's key must share them.
730
+ * What is remembered is a fact about a number rather than anything a caller supplied, so a hit is
731
+ * the same answer the test would give. The map is capped and cleared wholesale when it fills, which
732
+ * bounds it without giving a caller a way to decide what stays. */
733
+ var _PRIME_MEMO = new intrinsic.Map();
734
+ var _PRIME_MEMO_N = 0;
735
+
736
+ function _isPrime(n) {
737
+ var hit = intrinsic.mapGet(_PRIME_MEMO, n);
738
+ if (hit !== undefined) return hit;
739
+ var answer = _checkPrimeSync(_bigToBuf(n));
740
+ if (_PRIME_MEMO_N >= constants.LIMITS.DH_PRIME_MEMO_ENTRIES) {
741
+ _PRIME_MEMO = new intrinsic.Map();
742
+ _PRIME_MEMO_N = 0;
743
+ }
744
+ intrinsic.mapSet(_PRIME_MEMO, n, answer);
745
+ _PRIME_MEMO_N++;
746
+ return answer;
747
+ }
748
+
749
+ /** @internal A non-negative BigInt as the big-endian bytes the runtime's primality test reads. */
750
+ function _bigToBuf(n) {
751
+ var len = 0, v = n;
752
+ while (v > 0n) { len++; v >>= 8n; }
753
+ if (len === 0) len = 1;
754
+ var buf = intrinsic.bufferAlloc(len);
755
+ v = n;
756
+ for (var i = len - 1; i >= 0; i--) { buf[i] = Number(v & 0xffn); v >>= 8n; }
757
+ return buf;
758
+ }
759
+
760
+ /** @internal b^e mod m by square and multiply. The exponent is a public domain parameter and the
761
+ * base a public key, so no operand here is secret and the loop is not written to hide one. */
762
+ function _modPow(base, exp, mod) {
763
+ var result = 1n, b = base % mod, e = exp;
764
+ while (e > 0n) {
765
+ if (e & 1n) result = (result * b) % mod;
766
+ e >>= 1n;
767
+ b = (b * b) % mod;
768
+ }
769
+ return result;
770
+ }
771
+
772
+ /** @internal An X.509 Diffie-Hellman certificate names dhpublicnumber and carries X9.42
773
+ * DomainParameters (RFC 3279 sec. 2.3.3), where this runtime classifies only the PKCS#3 DHParameter
774
+ * form. The agreement needs p and g, so the key is rewritten into the form the runtime reads.
775
+ * DomainParameters also states q, the order of the subgroup the key is supposed to live in, which
776
+ * the PKCS#3 form cannot carry: it is checked HERE, before the parameter that states it is dropped.
777
+ * Without that check a key outside the subgroup would be agreed with, and the shared secret it
778
+ * produces leaks the private exponent modulo the small order it does have. */
779
+ function _x942ToPkcs3(spkiBytes, what) {
780
+ var parts = _spkiParts(spkiBytes);
781
+ if (parts === null || parts.algOid !== O("dhpublicnumber")) return null;
782
+ var node = parts.node;
783
+
784
+ var dom, y;
785
+ try {
786
+ dom = _x942Domain(parts.params, what);
787
+ /** @internal The public key BIT STRING holds whole octets. The codec admits a nonzero unused-bit
788
+ * count whose padding bits are zero, which spells one key two ways, and the conversion carries
789
+ * this BIT STRING through unchanged, so the second spelling would be re-emitted rather than
790
+ * normalized. */
791
+ var pub = asn1.read.bitString(node.children[1]);
792
+ if (!guard.crypto.isOctetAligned(pub)) {
793
+ throw _err("crmf/bad-popo", what + " Diffie-Hellman public key BIT STRING must be octet-aligned (0 unused bits)");
794
+ }
795
+ y = asn1.read.integer(asn1.decode(pub.bytes));
796
+ } catch (e3) {
797
+ if (e3 instanceof CrmfError) throw e3;
798
+ throw _err("crmf/bad-popo", what + " X9.42 Diffie-Hellman key could not be read", e3);
799
+ }
800
+ return {
801
+ p: dom.p, g: dom.g, y: y, q: dom.q, j: dom.j,
802
+ der: intrinsic.bufferFrom(b.sequence([
803
+ b.sequence([b.oid(O("dhKeyAgreement")), b.sequence([b.integer(dom.p), b.integer(dom.g)])]),
804
+ b.raw(node.children[1].bytes),
805
+ ])),
806
+ };
807
+ }
808
+
809
+ /** @internal How a key reads in the refusal above. A key the runtime imported without classifying
810
+ * carries no asymmetricKeyType, and reporting that as a type name says nothing an operator can act on. */
811
+ function _keyTypeLabel(what, key) {
812
+ var type = key && key.asymmetricKeyType;
813
+ if (typeof type !== "string" || type === "") {
814
+ return what + " carries an algorithm this runtime does not recognize as a key it can agree with";
815
+ }
816
+ return what + " is " + guard.text.showValue(type);
817
+ }
818
+
819
+ /** @internal Whether a decoded alternative-name extension names anybody. GeneralNames is a SEQUENCE
820
+ * of at least one GeneralName, and a GeneralName is a CHOICE whose every arm carries a
821
+ * context-specific tag from 0 to 8 (RFC 5280 sec. 4.2.1.6). The certificate parser surfaces an
822
+ * extension's bytes without running the decoder registered for it, so a list that is empty, or that
823
+ * holds something no arm of that CHOICE covers, reaches here carrying a length and naming nobody. */
824
+ function _namesSomebody(node) {
825
+ if (!_isUniversal(node, 16) || !node.children || node.children.length === 0) return false;
826
+ try { schema.walk(pkix.generalNames(NS, { code: "crmf/bad-popo" }), node, NS); }
827
+ catch (_e) { return false; } // allow:swallow-unverified a list the shared reader refuses names nobody, which the caller's refusal states
828
+ /** @internal The shared reader takes ediPartyName [5] as any non-empty constructed value, so a [5]
829
+ * holding a NULL passes it while encoding no name at all. EDIPartyName is SEQUENCE { nameAssigner
830
+ * [0] DirectoryString OPTIONAL, partyName [1] DirectoryString } (RFC 5280 sec. 4.2.1.6), so the
831
+ * arms it holds are context-tagged and a universal value is not one of them. x400Address [3] is an
832
+ * ORAddress, which this does not read, and is left to the shared reader: the derivation hashes
833
+ * these bytes rather than interpreting them, so an arm it cannot check is still an arm both sides
834
+ * hash alike. */
835
+ /** @internal Walked arm by arm, because the reader answers for most of them and not for all. It
836
+ * requires the IA5 arms [1] [2] [6] to carry characters, [7] to be an address of a real width and
837
+ * [8] to be an OBJECT IDENTIFIER, and it walks [0] and [4] into their own shapes. What it does not
838
+ * do is refuse the two empty forms below, and x400Address [3] it takes on its tag alone, which is
839
+ * left as it is: the derivation hashes these bytes rather than reading them, so an arm neither
840
+ * side reads is still an arm both sides hash alike. */
841
+ for (var i = 0; i < node.children.length; i++) {
842
+ var arm = node.children[i];
843
+ if (arm.tagNumber === 3 && !_isOrAddress(arm)) return false;
844
+ if (arm.tagNumber === 4 && !_isNonEmptyName(arm)) return false;
845
+ if (arm.tagNumber === 5 && !_isEdiPartyName(arm)) return false;
846
+ }
847
+ return true;
848
+ }
849
+
850
+ /** @internal Whether a [3] arm is an ORAddress that names somebody. It opens with the
851
+ * BuiltInStandardAttributes SEQUENCE (X.411), so an arm carrying that tag over some other value is
852
+ * not an address. Every field of those attributes is optional, and the domain-defined and extension
853
+ * attributes that may follow carry naming data of their own, so the address names somebody when ANY
854
+ * of its components does: an empty first component is a conforming address when a later one is not.
855
+ * What the components hold is an X.400 structure this does not read, which the derivation can afford
856
+ * because it hashes these bytes rather than interpreting them; what it cannot afford is hashing an
857
+ * address whose every component is empty, which names nobody at all. */
858
+ function _isOrAddress(node) {
859
+ var kids = node.children;
860
+ if (!kids || kids.length === 0 || !schema.isUniversal(kids[0], 16)) return false;
861
+ for (var i = 0; i < kids.length; i++) {
862
+ if (kids[i].children && kids[i].children.length > 0) return true;
863
+ }
864
+ return false;
865
+ }
866
+
867
+ /** @internal Whether a [4] arm names a directory entry. Name is a SEQUENCE OF RelativeDistinguished
868
+ * Name and permits none at all, which is the very thing the subject field carried when this fallback
869
+ * was reached: an empty name substituted for an empty name still names nobody. */
870
+ function _isNonEmptyName(node) {
871
+ var kids = node.children;
872
+ if (!kids || kids.length !== 1) return false;
873
+ var dn = kids[0];
874
+ return schema.isUniversal(dn, 16) && !!dn.children && dn.children.length > 0;
875
+ }
876
+
877
+ /** @internal The universal tags a DirectoryString is written under (RFC 5280 sec. 4.1.2.4):
878
+ * UTF8String, PrintableString, TeletexString, UniversalString and BMPString. */
879
+ var DIRECTORY_STRING_TAGS = [12, 19, 20, 28, 30];
880
+
881
+ /** @internal Whether a [5] arm holds an EDIPartyName: the optional nameAssigner [0] before the
882
+ * required partyName [1], each carrying a DirectoryString. DirectoryString is a CHOICE, so its tag
883
+ * is EXPLICIT however the module tags: the arm is constructed and wraps the string itself, and the
884
+ * string has to be one, since a [1] wrapping a NULL is tagged like a name and holds none. */
885
+ function _isEdiPartyName(node) {
886
+ var kids = node.children;
887
+ if (!kids || kids.length < 1 || kids.length > 2) return false;
888
+ for (var i = 0; i < kids.length; i++) {
889
+ var arm = kids[i];
890
+ if (!schema.isContextInRange(arm, 0, 1) || !arm.children || arm.children.length !== 1) return false;
891
+ if (!schema.isUniversalOneOf(arm.children[0], DIRECTORY_STRING_TAGS)) return false;
892
+ /** @internal Read as the string it is tagged as, not counted as one. DirectoryString is
893
+ * SIZE (1..MAX), so an empty one names nobody, and a string whose bytes are not the encoding its
894
+ * tag claims is not a name either. The codec's own reader answers both. */
895
+ var text;
896
+ try { text = asn1.read.string(arm.children[0]); }
897
+ catch (_e) { return false; } // allow:swallow-unverified a string the codec cannot read names nobody, which the caller's refusal states
898
+ if (text.length === 0) return false;
899
+ }
900
+ if (kids.length === 2) return kids[0].tagNumber === 0 && kids[1].tagNumber === 1;
901
+ return kids[0].tagNumber === 1;
902
+ }
903
+
904
+ function _nameOrAlternative(parsed, nameField, altExtension) {
905
+ var name = parsed[nameField];
906
+ if (name && name.bytes && name.rdns && name.rdns.length > 0) return intrinsic.bufferFrom(name.bytes);
907
+ var exts = parsed.extensions;
908
+ for (var i = 0; exts && i < exts.length; i++) {
909
+ var ext = exts[i];
910
+ if (ext && ext.name === altExtension && ext.value != null) {
911
+ var alt = _b.reqDer(ext.value, "the authority certificate's " + altExtension);
912
+ /** @internal Read through the GeneralNames schema, not measured. The certificate parser
913
+ * surfaces an extension's bytes without running the decoder registered for it, so a
914
+ * present-but-empty list carries a length while naming nobody, and a SEQUENCE holding
915
+ * something that is not a GeneralName names nobody either. Keying the derivation from bytes
916
+ * like those is the case this refusal exists for. */
917
+ var altNames;
918
+ try { altNames = asn1.decode(alt); } catch (_e) { altNames = null; } // allow:swallow-unverified a list this cannot read names nobody, which the refusal below states
919
+ if (_namesSomebody(altNames)) {
920
+ return intrinsic.bufferFrom(alt);
921
+ }
922
+ }
923
+ }
924
+ throw _err("crmf/bad-popo", "the authority certificate's " + nameField +
925
+ " name is empty and it carries no " + altExtension + " to use in its place (RFC 4211 sec. 4.3)");
926
+ }
927
+
928
+ function _buildPopoPrivKey(pop, mode, template, certReqDer) {
161
929
  var outerTag = POPO_PRIVKEY_TAGS[guard.text.keyOf(mode)];
162
930
  var method = pop && pop.method;
163
931
  if (typeof method !== "string") {
@@ -171,11 +939,7 @@ function _buildPopoPrivKey(pop, mode, template) {
171
939
  throw _err("crmf/bad-popo", "keyEncipherment proof of possession cannot use the agreeMAC alternative -- " +
172
940
  "it is defined for keyAgreement only (RFC 4211 sec. 4.2, sec. 4.3)");
173
941
  }
174
- if (method === "agreeMAC") {
175
- throw _err("crmf/unsupported-popo", "the agreeMAC proof of possession is not built by this toolkit: it requires " +
176
- "the RFC 2875 static Diffie-Hellman shared secret between the requester's key and a CA certificate it " +
177
- "already holds. Use 'subsequentMessage' (encrCert or challengeResp), which every key type can produce");
178
- }
942
+ if (method === "agreeMAC") return _buildAgreeMac(pop, outerTag, certReqDer, template);
179
943
  if (method === "subsequentMessage") {
180
944
  var which = pop.subsequentMessage;
181
945
  if (typeof which !== "string" || !_hasOwn(SUBSEQUENT_MESSAGE, which)) {
@@ -257,6 +1021,38 @@ function _assertEnclosedKeyMatches(privateKeyDer, templateSpki) {
257
1021
  .then(function (derivedSpki) {
258
1022
  var derived = guard.bytes.view(derivedSpki, CrmfError, "crmf/bad-input", "the derived public key");
259
1023
  var wanted = guard.bytes.view(templateSpki, CrmfError, "crmf/bad-input", "certTemplate.publicKey");
1024
+ /** @internal A finite-field key names itself in either encoding here too, and an enclosed key
1025
+ * derives its public half in the PKCS#3 form, so a template naming the X9.42 form is brought to
1026
+ * the one form rather than read as a different key, and one already in the PKCS#3 form is read
1027
+ * where it stands. Both are held to describing the key they carry, since the request travels
1028
+ * with them. Neither is held to the floors the AGREEMENT needs: this arm sends a private key to
1029
+ * be archived and agrees nothing, so those would refuse a legacy key it exists to enroll. */
1030
+ /** @internal Both encodings are read for their SHAPE, so a request does not travel carrying
1031
+ * DER nothing checked, and the X9.42 form is brought to the one the runtime classifies so the
1032
+ * comparison is about keys. This arm asks one question, which RFC 4211 sec. 4.2 states: is the
1033
+ * enclosed key the private half of the requested one. Whether that key sits in a good group is
1034
+ * the certifying authority's policy, and answering it here would mean proving a modulus prime,
1035
+ * which costs seconds and forces an upper bound on the size, so a key too large to prove would
1036
+ * become a key too large to archive.
1037
+ * What a stated order and cofactor say about the p and g beside them is a different question,
1038
+ * and it is answered: the conversion drops both, the request travels carrying the caller's own
1039
+ * encoding of them, and the tests take a multiplication and a modulo rather than the
1040
+ * exponentiation and the primality proofs the size bound exists for. */
1041
+ var wantedX942 = _x942ToPkcs3(wanted, "certTemplate.publicKey's");
1042
+ if (wantedX942 !== null) {
1043
+ _assertDhParamsCoherent(wantedX942.p, wantedX942.g, wantedX942.q, wantedX942.j, "certTemplate.publicKey's");
1044
+ wanted = wantedX942.der;
1045
+ } else _pkcs3Params(wanted, "certTemplate.publicKey's");
1046
+ /** @internal Both sides, not one. An enclosed key in the X9.42 form derives its public half in
1047
+ * that same form, so converting only the template would compare one encoding against the other
1048
+ * and refuse a pair that matches. The order and cofactor this side states are the enclosed
1049
+ * private key's own, and they reach the archive with it, so the same conversion drops them under
1050
+ * the same tests rather than only where the caller wrote the parameters by hand. */
1051
+ var derivedX942 = _x942ToPkcs3(derived, "the enclosed private key's");
1052
+ if (derivedX942 !== null) {
1053
+ _assertDhParamsCoherent(derivedX942.p, derivedX942.g, derivedX942.q, derivedX942.j, "the enclosed private key's");
1054
+ derived = derivedX942.der;
1055
+ }
260
1056
  if (!_b.samePublicKey(derived, wanted)) {
261
1057
  throw _err("crmf/bad-popo", "the private key enclosed in the encryptedKey proof of possession is not the " +
262
1058
  "private half of certTemplate.publicKey, so it proves possession of a key this request does not ask to " +
@@ -298,7 +1094,7 @@ function _assertPopArmKeys(pop, mode) {
298
1094
  }
299
1095
 
300
1096
  function _buildProofOfPossession(pop, certReqDer, template, signingKey, opts) {
301
- if (pop != null && (typeof pop !== "object" || Buffer.isBuffer(pop))) throw _err("crmf/bad-input", "spec.pop must be an object (e.g. { type: 'signature' } or { type: 'raVerified', raVerified: true })");
1097
+ if (pop != null && (typeof pop !== "object" || _isBuffer(pop))) throw _err("crmf/bad-input", "spec.pop must be an object (e.g. { type: 'signature' } or { type: 'raVerified', raVerified: true })");
302
1098
  var mode = (pop && pop.type) || (signingKey != null ? "signature" : null);
303
1099
  if (pop != null) _assertPopArmKeys(pop, mode);
304
1100
  if (mode == null) return null;
@@ -306,7 +1102,7 @@ function _buildProofOfPossession(pop, certReqDer, template, signingKey, opts) {
306
1102
  if (!(pop && pop.raVerified === true)) throw _err("crmf/bad-popo", "raVerified must be explicitly opted into (pop: { type: 'raVerified', raVerified: true }) -- a requester does not normally assert it (RFC 4211 sec. 4)");
307
1103
  return b.implicit(0, b.nullValue());
308
1104
  }
309
- if (_hasOwn(POPO_PRIVKEY_TAGS, guard.text.keyOf(mode))) return _buildPopoPrivKey(pop, mode, template);
1105
+ if (_hasOwn(POPO_PRIVKEY_TAGS, guard.text.keyOf(mode))) return _buildPopoPrivKey(pop, mode, template, certReqDer);
310
1106
  if (mode !== "signature") {
311
1107
  throw _err("crmf/bad-popo", "unsupported proof-of-possession type " + guard.text.showValue(mode) +
312
1108
  " (supported: 'signature', 'raVerified', 'keyEncipherment', 'keyAgreement')");
@@ -376,13 +1172,20 @@ function _buildProofOfPossession(pop, certReqDer, template, signingKey, opts) {
376
1172
  * sec. 4.2.1 makes it mandatory whenever the purpose is proving possession: without it a decrypting
377
1173
  * agent cannot tell whose key it holds. `pop.contentEncryptionAlgorithm` defaults to `aes-256-cbc`; an
378
1174
  * AEAD algorithm is refused, since it would produce an `AuthEnvelopedData` this field cannot carry.
1175
+ * - `agreeMAC`, which agrees a secret with the authority and MACs the request under a key derived from it,
1176
+ * so nothing is signed (RFC 4211 sec. 4.3, RFC 2875 sec. 3). `pop.key` is the requester's finite-field
1177
+ * Diffie-Hellman private key, as a PKCS#8 DER, a PEM `PRIVATE KEY` block, or a `KeyObject`, and
1178
+ * `pop.caCert` is the authority's certificate the requester already holds, as DER or a PEM
1179
+ * `CERTIFICATE` block. Either key may name its group in the PKCS#3 or the X9.42 encoding.
1180
+ * `pop.key` must be the private half of `certTemplate.publicKey`,
1181
+ * which the authority derives its own side of the agreement from, and the template must name both a
1182
+ * subject and a public key, which the MAC covers. An elliptic-curve or montgomery pair is refused, as is
1183
+ * a key on parameters other than the authority's.
379
1184
  *
380
1185
  * The two alternatives the specification deprecates in the same breath as defining them, `thisMessage` and
381
1186
  * `dhMAC`, are refused with their successors named; `pki.schema.crmf.parse` still reads both, since a peer
382
- * may send one. `agreeMAC` is not built: it needs the RFC 2875 static Diffie-Hellman shared secret between
383
- * the requester's key and a CA certificate it already holds. Building an `encryptedKey` or `agreeMAC` proof
384
- * inside `pki.cmp.build` raises the announced protocol version to cmp2021(3), which RFC 9810 sec. 5.2.8.3
385
- * requires.
1187
+ * may send one. Building an `encryptedKey` or `agreeMAC` proof inside `pki.cmp.build` raises the announced
1188
+ * protocol version to cmp2021(3), which RFC 9810 sec. 5.2.8.3 requires.
386
1189
  *
387
1190
  * @opts
388
1191
  * - `pem` (string) -- return a PEM block with this label instead of DER (e.g. "CERTIFICATE REQUEST MESSAGE").
@@ -404,11 +1207,11 @@ function build(spec, key, opts) {
404
1207
  }
405
1208
 
406
1209
  function _buildCertReqMsg(spec, key, opts) {
407
- if (!spec || typeof spec !== "object" || Buffer.isBuffer(spec)) throw _err("crmf/bad-input", "each certificate-request-message spec must be an object");
1210
+ if (!spec || typeof spec !== "object" || _isBuffer(spec)) throw _err("crmf/bad-input", "each certificate-request-message spec must be an object");
408
1211
  guard.identifier.assertKnownKeys(spec, KNOWN_SPEC_KEYS, _err, "crmf/bad-input", "unknown spec field ");
409
1212
  if (spec.certTemplate == null) throw _err("crmf/bad-input", "spec.certTemplate is required");
410
1213
 
411
- var signingKey = (key && typeof key === "object" && !Buffer.isBuffer(key) && !(key instanceof Uint8Array) && key.type == null && "key" in key) ? key.key : key;
1214
+ var signingKey = (key && typeof key === "object" && !_isBuffer(key) && !(key instanceof Uint8Array) && key.type == null && "key" in key) ? key.key : key;
412
1215
  var template = _encodeCertTemplate(spec.certTemplate);
413
1216
  var certReqChildren = [b.integer(_certReqId(spec.certReqId)), template.der];
414
1217
  if (spec.controls != null) certReqChildren.push(_buildAttrTypeAndValues(spec.controls, "crmf/bad-controls", "controls", CONTROL_VALUE));
@@ -424,7 +1227,7 @@ function _buildCertReqMsg(spec, key, opts) {
424
1227
 
425
1228
  function _build(spec, key, opts) {
426
1229
  opts = opts || {};
427
- if (!spec || typeof spec !== "object" || Buffer.isBuffer(spec)) throw _err("crmf/bad-input", "the certificate-request-message spec must be an object");
1230
+ if (!spec || typeof spec !== "object" || _isBuffer(spec)) throw _err("crmf/bad-input", "the certificate-request-message spec must be an object");
428
1231
  var specs;
429
1232
  if (spec.messages != null) {
430
1233
  if (!Array.isArray(spec.messages)) throw _err("crmf/bad-input", "spec.messages must be an array of certificate-request-message specs");
package/lib/oid.js CHANGED
@@ -192,6 +192,13 @@ var FAMILIES = Object.assign(Object.create(null), {
192
192
  entrustAlg: { base: [1, 2, 840, 113533, 7, 66], of: {
193
193
  passwordBasedMac: 13, kemBasedMac: 16, dhBasedMac: 30 } },
194
194
 
195
+ /** @internal ANSI X9.42 (RFC 3279 sec. 2.3.3): the SubjectPublicKeyInfo algorithm an X.509
196
+ * Diffie-Hellman certificate names, whose parameters are DomainParameters rather than the PKCS#3
197
+ * DHParameter that pkcs3 below names. */
198
+ ansiX942: { base: [1, 2, 840, 10046, 2], of: { dhpublicnumber: 1 } },
199
+
200
+ pkcs3: { base: [1, 2, 840, 113549, 1, 3], of: { dhKeyAgreement: 1 } },
201
+
195
202
  pkcs12BagTypes: { base: [1, 2, 840, 113549, 1, 12, 10, 1], of: {
196
203
  keyBag: 1, pkcs8ShroudedKeyBag: 2, certBag: 3, crlBag: 4, secretBag: 5, safeContentsBag: 6 } },
197
204
 
@@ -226,6 +233,7 @@ var FAMILIES = Object.assign(Object.create(null), {
226
233
 
227
234
  pkixAlg: { base: [1, 3, 6, 1, 5, 5, 7, 6], of: {
228
235
  "id-alg-noSignature": 2,
236
+ "id-dhPop-static-HMAC-SHA1": 3, "id-alg-dhPOP": 4,
229
237
  "id-RSASSA-PSS-SHAKE128": 30, "id-RSASSA-PSS-SHAKE256": 31,
230
238
  "id-alg-xmss-hashsig": 34, "id-alg-xmssmt-hashsig": 35,
231
239
  "id-MLDSA44-RSA2048-PSS-SHA256": 37, "id-MLDSA44-RSA2048-PKCS15-SHA256": 38,
@@ -182,7 +182,22 @@ function pemDecodeLenient(text, label) {
182
182
  return _bufferFrom(_keepBase64(_strSlice(text, bodyStart, ei)), "base64");
183
183
  }
184
184
 
185
+ /** @internal Every refusal below is built from opts, so opts is checked before the first one can be
186
+ * reached. A caller that misspells a key otherwise gets a working accept path and a set of refusal
187
+ * paths that throw `undefined is not a constructor`: the input is still rejected, but as an untyped
188
+ * runtime error carrying no reason, and the label check silently passes everything. */
189
+ function _requireCoerceOpts(opts) {
190
+ if (!opts || typeof opts !== "object") throw new TypeError("coerceToDer requires an options object");
191
+ if (typeof opts.PemError !== "function") throw new TypeError("coerceToDer requires opts.PemError, an error constructor");
192
+ if (typeof opts.ErrorClass !== "function") throw new TypeError("coerceToDer requires opts.ErrorClass, an error constructor");
193
+ if (typeof opts.prefix !== "string" || opts.prefix === "") throw new TypeError("coerceToDer requires opts.prefix, a non-empty error-code prefix");
194
+ if (!(opts.pemLabel === null || typeof opts.pemLabel === "string")) {
195
+ throw new TypeError("coerceToDer requires opts.pemLabel, a PEM label to enforce or null to accept any");
196
+ }
197
+ }
198
+
185
199
  function coerceToDer(input, opts) {
200
+ _requireCoerceOpts(opts);
186
201
  if (typeof input === "string") return pemDecode(input, opts.pemLabel, opts.PemError);
187
202
  if (guard.bytes.isByteSource(input)) {
188
203
  var buf = guard.bytes.source(input, opts.ErrorClass, opts.prefix + "/bad-input", "parse");
package/lib/sigstore.js CHANGED
@@ -42,6 +42,15 @@ var C = constants;
42
42
  var SigstoreError = frameworkError.SigstoreError;
43
43
  function _err(code, message, cause) { return new SigstoreError(code, message, cause); }
44
44
 
45
+ /** @internal Whether a oneof arm is PRESENT, which is not the same as whether it is truthy. A bundle
46
+ * setting an arm to false or to an empty string has set it: reading presence as truthiness lets a
47
+ * second arm sit beside the one being read, which is the state the oneof rule exists to refuse. Own
48
+ * properties only, so a polluted prototype cannot conjure an arm the bundle does not carry. */
49
+ function _armPresent(obj, name) {
50
+ return !!obj && typeof obj === "object" &&
51
+ Object.prototype.hasOwnProperty.call(obj, name) && obj[name] !== undefined && obj[name] !== null;
52
+ }
53
+
45
54
  var JSON_MAX = C.LIMITS.JSON_MAX_BYTES;
46
55
  var SP = Buffer.from(" ", "ascii");
47
56
  var DSSEV1 = Buffer.from("DSSEv1", "ascii");
@@ -170,7 +179,24 @@ function parseBundle(input) {
170
179
  if (!obj.verificationMaterial || typeof obj.verificationMaterial !== "object") {
171
180
  throw _err("sigstore/bad-bundle", "bundle is missing verificationMaterial");
172
181
  }
173
- if (obj.messageSignature && !obj.dsseEnvelope) {
182
+ /** @internal The verification material's certificate is a oneof of the same kind. Both arms set
183
+ * draws the leaf from one and the chain from the other, so the certificate whose key is checked and
184
+ * the certificates it is checked through come from different statements about the same signer. */
185
+ var vmArms = 0;
186
+ if (_armPresent(obj.verificationMaterial, "certificate")) vmArms++;
187
+ if (_armPresent(obj.verificationMaterial, "x509CertificateChain")) vmArms++;
188
+ if (_armPresent(obj.verificationMaterial, "publicKey")) vmArms++;
189
+ if (vmArms > 1) {
190
+ throw _err("sigstore/bad-bundle", "verificationMaterial carries more than one of certificate, x509CertificateChain and publicKey; it is a oneof and exactly one arm may be present");
191
+ }
192
+ /** @internal The bundle's content is a protobuf oneof, so a bundle setting both arms is malformed
193
+ * and is refused rather than read as whichever arm this build happens to support: verifying the
194
+ * envelope and passing over the other arm reports a verdict that says nothing about content the
195
+ * bundle carries. The two refusals are separate because a caller can act on one and not the other. */
196
+ if (_armPresent(obj, "messageSignature") && _armPresent(obj, "dsseEnvelope")) {
197
+ throw _err("sigstore/bad-bundle", "bundle carries both dsse_envelope and message_signature; the bundle content is a oneof and exactly one arm may be present");
198
+ }
199
+ if (_armPresent(obj, "messageSignature")) {
174
200
  throw _err("sigstore/unsupported-content", "a message_signature bundle is not supported (only dsse_envelope)");
175
201
  }
176
202
  if (!obj.dsseEnvelope || typeof obj.dsseEnvelope !== "object") {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blamejs/pki",
3
- "version": "0.6.54",
3
+ "version": "0.6.55",
4
4
  "description": "Pure-JavaScript PKI toolkit that owns its stack — X.509, ASN.1/DER, CMS, PQC-first.",
5
5
  "license": "Apache-2.0",
6
6
  "author": "blamejs contributors",
package/sbom.cdx.json CHANGED
@@ -2,10 +2,10 @@
2
2
  "$schema": "http://cyclonedx.org/schema/bom-1.5.schema.json",
3
3
  "bomFormat": "CycloneDX",
4
4
  "specVersion": "1.5",
5
- "serialNumber": "urn:uuid:3fcb367d-0079-41f4-bd25-0141050006d7",
5
+ "serialNumber": "urn:uuid:03ece622-aaca-4a54-b858-4ae7bbb58893",
6
6
  "version": 1,
7
7
  "metadata": {
8
- "timestamp": "2026-09-07T18:01:28.536Z",
8
+ "timestamp": "2026-09-08T07:28:55.626Z",
9
9
  "lifecycles": [
10
10
  {
11
11
  "phase": "build"
@@ -19,14 +19,14 @@
19
19
  }
20
20
  ],
21
21
  "component": {
22
- "bom-ref": "@blamejs/pki@0.6.54",
22
+ "bom-ref": "@blamejs/pki@0.6.55",
23
23
  "type": "application",
24
24
  "name": "pki",
25
- "version": "0.6.54",
25
+ "version": "0.6.55",
26
26
  "scope": "required",
27
27
  "author": "blamejs contributors",
28
28
  "description": "Pure-JavaScript PKI toolkit that owns its stack — X.509, ASN.1/DER, CMS, PQC-first.",
29
- "purl": "pkg:npm/%40blamejs/pki@0.6.54",
29
+ "purl": "pkg:npm/%40blamejs/pki@0.6.55",
30
30
  "properties": [],
31
31
  "externalReferences": [
32
32
  {
@@ -54,7 +54,7 @@
54
54
  "components": [],
55
55
  "dependencies": [
56
56
  {
57
- "ref": "@blamejs/pki@0.6.54",
57
+ "ref": "@blamejs/pki@0.6.55",
58
58
  "dependsOn": []
59
59
  }
60
60
  ]