@blamejs/pki 0.7.38 → 0.7.40

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,24 @@ 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.7.40 — 2026-09-12
8
+
9
+ A PKCS#12 store links a certificate only to its own key.
10
+
11
+ ### Changed
12
+
13
+ - pki.pkcs12.build refuses, with pkcs12/bad-input, a { key, cert } pair whose key is not the private half of the certificate's public key, and a key bag and a certificate bag sharing a localKeyId (PKCS #9 sec. 5.5.2) whose key is not that certificate's, across every safe and nested safe of the store. The pair is proven with the private material (a signature, an agreement, or for a composite ML-KEM key an encapsulation to the certificate's key decapsulated under the private key), never by the public components a private key carries about itself. A localKeyId names one private key, so a store carrying one localKeyId on two key bags is refused with pkcs12/bad-input; several certificate bags under one key's localKeyId are each held to that key, at most 1024 across the store. A store of more than 1024 safes is refused before any safe is built. Bags with different or absent localKeyIds are not a pair and are unaffected; a key-only or certificate-only store is unaffected.
14
+ - The toolkit proves a finite-field Diffie-Hellman key pair by the public value the exponent generates (a DH PrivateKeyInfo carries the exponent alone), in either encoding of the key: the PKCS #3 form a generated key is written in and the X9.42 form a certificate names it in (RFC 3279 sec. 2.3.3); a key in either encoding is held to the largest group the toolkit agrees over (4096 bits) and to a group whose modulus and stated order are prime, so a malformed DH certificate is refused rather than paired. Proving a DH pair costs those primality proofs, so a store links at most 8 finite-field DH pairs. So pki.pkcs12.build stores a DH key with its certificate and a CMP session confirms a centrally generated DH key the issued certificate certifies; a DH key under another key's certificate is refused as before.
15
+
16
+ ## v0.7.39 — 2026-09-12
17
+
18
+ An OCSP CertID's issuer hashes are held to the length of the digest they name.
19
+
20
+ ### Changed
21
+
22
+ - pki.schema.ocsp.parseRequest and parseResponse refuse a CertID whose issuerNameHash or issuerKeyHash is not the length of the digest its hashAlgorithm names (ocsp/bad-cert-id, RFC 6960 sec. 4.1.1), for SHA-1, SHA-256, SHA-384, SHA-512, SHA3-256 and SHA3-512; a CertID under a digest this build does not know is read as given. pki.ocsp.verify and pki.ocsp.verifyRequest, which parse first, report such a request or response as malformed instead of comparing a hash that could never match.
23
+ - The digest output lengths live in pki.constants.NAMES.DIGEST_OCTETS, read by the OCSP parser and by pki.tsp.sign and pki.tsp.verify for the messageImprint length check they already made.
24
+
7
25
  ## v0.7.38 — 2026-09-12
8
26
 
9
27
  pki.lint.certificate grades six RFC 5280 rules its parser read past, and the parser surfaces the unique identifiers.
package/README.md CHANGED
@@ -238,7 +238,7 @@ comment blocks, is at [pkijs.com](https://pkijs.com).
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 MAC algorithm it does not compute (reported as MAC-protected under that algorithm, never as a failed signature), 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, issuer alternative name, issuing distribution point, delta-CRL indicator, freshest CRL, authority information access, which is every extension RFC 5280 §5.2 defines) or an array of pre-encoded Extension DER, with an `issuer` of `{ cert, key }` or `{ name, publicKey, key }`. The authority key identifier is emitted on every CRL whether or not it is named, as §5.2.1 places it on every conforming issuer, from the issuer certificate's SKI or the issuer 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` |
241
- | `pki.pkcs12` | PKCS#12 (.p12/.pfx) issuance and reading (RFC 7292 / RFC 9579). `build(spec, opts)` assembles a store from the OpenSSL-style `{ key, cert, ca?, friendlyName?, localKeyId? }` or the full `{ safeContents: [...] }`, where each element is a plaintext or PBES2-encrypted `SafeContents` of key, shroudedKey, cert, crl, secret, or nested `safeContents` bags. Keys and certs are validated before wrapping, and `friendlyName` (BMPString) and `localKeyId` are single-value. Integrity is a classic Appendix B HMAC (the default, for maximum interoperability) or an RFC 9579 PBMAC1 (`opts.mac.algorithm`) over SHA-256/384/512, with shrouded keys and cert safes encrypted under RFC 8018 PBES2 (AES-128/192/256-CBC). Every password is encoded the PKCS#12 way — BMPString+NULL for the classic MAC, UTF-8 for the PBES2 bags and PBMAC1 — which is what OpenSSL and NSS consume, so a file it emits opens in both, cross-checked bidirectionally. The MAC covers the exact AuthenticatedSafe byte range, a DEFAULT-1 `MacData.iterations` is rejected up front, and the store is re-parsed before return. `verifyMac(pfx, password, opts)` recomputes a classic or PBMAC1 MAC over `macedBytes` and constant-time-compares it, throwing on a MAC-less or public-key-integrity store. Public-key integrity (`opts.integrity.mode: "public-key"`) wraps the AuthenticatedSafe in a CMS SignedData instead of a MAC, signed by any `pki.cms.sign` signer and carrying no MacData (§4); privacy stays independent, so `password` still PBES2-encrypts the bags. Public-key privacy wraps a SafeContents as a CMS EnvelopedData (AES-CBC, `id-envelopedData`, never GCM) encrypted to recipient public keys through the `pki.cms.encrypt` recipient model, via per-safe `recipients` or the `opts.recipientCerts` convenience, restricted to certificate recipients (RSA-OAEP, ECDH, X25519, X448, ML-KEM) since a password or KEK recipient could not be reopened by `open`. All four integrity-by-privacy combinations are permitted (§3.1). `open(pfx, password, opts)` reads a store back: it verifies the MAC first, so a wrong password is the MAC verdict rather than a decrypt error, then PBES2-decrypts every privacy safe and shrouded key bag and returns `{ integrityMode, macVerified, signers, keys, certs, crls, secrets }` — keys as re-validated PKCS#8 DER, certs, CRLs and secrets as raw DER, all with `friendlyName` and `localKeyId`, nested safes recursively. A MAC-less store is refused unless `opts.allowUnauthenticated`. A public-key-integrity store is verified through its CMS SignedData signature first (`pkcs12/signature-invalid` on failure), with the signer surfaced in `signers` but never trust-chained, which remains the caller's `pki.path.validate` step. A legacy-PBE store's Appendix C 3DES and RC2 bags are decrypted, RC2 through an in-tree RFC 2268 cipher, so an `openssl pkcs12 -legacy` or NSS store opens; the legacy RC4 schemes are refused. An `id-envelopedData` safe is decrypted with `opts.recipientKey` after the integrity gate (`pkcs12/no-recipient-key` when absent), every recipient-side fault and every post-integrity decrypt failure collapsing to the uniform `pkcs12/decrypt-failed`, and `opts.keys: 'crypto'` imports each key to a `CryptoKey`. It reads what OpenSSL and NSS produce. Returns DER or a PEM `PKCS12`, with a typed `Pkcs12Error` on failure. Parsing stays at `pki.schema.pkcs12.parse` — `build`, `verifyMac`, `open` |
241
+ | `pki.pkcs12` | PKCS#12 (.p12/.pfx) issuance and reading (RFC 7292 / RFC 9579). `build(spec, opts)` assembles a store from the OpenSSL-style `{ key, cert, ca?, friendlyName?, localKeyId? }` or the full `{ safeContents: [...] }`, where each element is a plaintext or PBES2-encrypted `SafeContents` of key, shroudedKey, cert, crl, secret, or nested `safeContents` bags. Keys and certs are validated before wrapping, a key paired with a certificate (the `{ key, cert }` form, or bags sharing a `localKeyId`) must be the private half of that certificate's public key, and `friendlyName` (BMPString) and `localKeyId` are single-value. Integrity is a classic Appendix B HMAC (the default, for maximum interoperability) or an RFC 9579 PBMAC1 (`opts.mac.algorithm`) over SHA-256/384/512, with shrouded keys and cert safes encrypted under RFC 8018 PBES2 (AES-128/192/256-CBC). Every password is encoded the PKCS#12 way — BMPString+NULL for the classic MAC, UTF-8 for the PBES2 bags and PBMAC1 — which is what OpenSSL and NSS consume, so a file it emits opens in both, cross-checked bidirectionally. The MAC covers the exact AuthenticatedSafe byte range, a DEFAULT-1 `MacData.iterations` is rejected up front, and the store is re-parsed before return. `verifyMac(pfx, password, opts)` recomputes a classic or PBMAC1 MAC over `macedBytes` and constant-time-compares it, throwing on a MAC-less or public-key-integrity store. Public-key integrity (`opts.integrity.mode: "public-key"`) wraps the AuthenticatedSafe in a CMS SignedData instead of a MAC, signed by any `pki.cms.sign` signer and carrying no MacData (§4); privacy stays independent, so `password` still PBES2-encrypts the bags. Public-key privacy wraps a SafeContents as a CMS EnvelopedData (AES-CBC, `id-envelopedData`, never GCM) encrypted to recipient public keys through the `pki.cms.encrypt` recipient model, via per-safe `recipients` or the `opts.recipientCerts` convenience, restricted to certificate recipients (RSA-OAEP, ECDH, X25519, X448, ML-KEM) since a password or KEK recipient could not be reopened by `open`. All four integrity-by-privacy combinations are permitted (§3.1). `open(pfx, password, opts)` reads a store back: it verifies the MAC first, so a wrong password is the MAC verdict rather than a decrypt error, then PBES2-decrypts every privacy safe and shrouded key bag and returns `{ integrityMode, macVerified, signers, keys, certs, crls, secrets }` — keys as re-validated PKCS#8 DER, certs, CRLs and secrets as raw DER, all with `friendlyName` and `localKeyId`, nested safes recursively. A MAC-less store is refused unless `opts.allowUnauthenticated`. A public-key-integrity store is verified through its CMS SignedData signature first (`pkcs12/signature-invalid` on failure), with the signer surfaced in `signers` but never trust-chained, which remains the caller's `pki.path.validate` step. A legacy-PBE store's Appendix C 3DES and RC2 bags are decrypted, RC2 through an in-tree RFC 2268 cipher, so an `openssl pkcs12 -legacy` or NSS store opens; the legacy RC4 schemes are refused. An `id-envelopedData` safe is decrypted with `opts.recipientKey` after the integrity gate (`pkcs12/no-recipient-key` when absent), every recipient-side fault and every post-integrity decrypt failure collapsing to the uniform `pkcs12/decrypt-failed`, and `opts.keys: 'crypto'` imports each key to a `CryptoKey`. It reads what OpenSSL and NSS produce. Returns DER or a PEM `PKCS12`, with a typed `Pkcs12Error` on failure. Parsing stays at `pki.schema.pkcs12.parse` — `build`, `verifyMac`, `open` |
242
242
  | `pki.cms` | CMS signing, verification, encryption, and compression (RFC 5652). `sign(content, signers, opts)` produces a SignedData (§5), attached or detached, with one or many signers over RSA, RSASSA-PSS, ECDSA, EdDSA, the post-quantum ML-DSA-44/65/87 (RFC 9882) and SLH-DSA (all twelve FIPS 205 sets, RFC 9814), and composite ML-DSA pairing ML-DSA with a traditional RSA, ECDSA, or EdDSA key (accepted only when both components verify, draft-ietf-lamps-cms-composite-sigs). It builds the signed attributes (content-type, message-digest, signing-time) as canonical DER, signs the exact §5.4 preimage, and emits a DER `Buffer` or PEM. The content may also be an async iterable of byte chunks, which signs a large detached payload without holding it in memory: the payload is hashed incrementally under every signer's digest algorithm in one pass, and `verify` accepts the same streamed form as its `content` option. A signer may also be key-only — `{ key, spki, keyIdentifier }` with no certificate — which RFC 5272 §3.2 requires when a Full PKI Request's signer is the key of a certification request that request carries: the signer identifier takes the subjectKeyIdentifier form carrying the identifier the request declares, the signature scheme resolves from the request's own public key, and no certificate is embedded. `verify(input, opts)` parses a SignedData over the strict `pki.schema.cms` codec, locates each SignerInfo's signer certificate by its issuerAndSerialNumber or subjectKeyIdentifier, and checks the signature over the exact §5.4 preimage: with signed attributes present it confirms the message-digest attribute equals the content digest and verifies over the DER re-encoding of the SignedAttributes (the on-wire `[0]` tag replaced by a universal SET OF), and otherwise directly over the content. It returns a per-signer verdict with the matched signer certificate. `valid` and `trusted` are separate claims and neither implies the other: a SignedData carries its own certificates, so `valid` says the signature is sound under one of them and nothing about who signed, while `trusted` says every signer chained to a root named in `opts.trustAnchors`, validated through the same RFC 5280 path engine `pki.path.validate` uses. Without anchors there is nothing to chain to and `trusted` is `false`; anchors that cannot be read throw, rather than reading as untrusted. An unrecognized option is refused rather than ignored. `countersign(cms, signers, opts)` adds a countersignature (§11.4) — a `SignerInfo` over the countersigned SignerInfo's signature value, any signer algorithm, nestable, with the primary bytes preserved so it still verifies — attached as the id-countersignature unsigned attribute; `verify` returns each countersignature's verdict under `signers[i].countersignatures` and every unsigned attribute — including an RFC 3161 timestamp token, attachable via `sign`'s `unsignedAttributes` — under `signers[i].unsignedAttrs`, surfaced unauthenticated. `encrypt(content, recipients, opts)` produces an EnvelopedData, AuthEnvelopedData (AES-GCM, the authenticated default), or EncryptedData, with recipients auto-dispatched off the certificate key to key transport (RSAES-OAEP; v1.5 is never emitted), key agreement (ephemeral-static ECDH over P-256/384/521 with the X9.63 KDF, and X25519/X448 with HKDF), symmetric key wrap, password (PBKDF2 with RFC 3211 PWRI-KEK), or the post-quantum ML-KEM (and composite ML-KEM, draft-lamps-pq-composite-kem) KEMRecipientInfo (RFC 9629/9936), wrapping one fresh content key for every recipient. The content may also be an async iterable of byte chunks, streamed through the AES-GCM or AES-CBC content cipher so a large plaintext is encrypted without being buffered whole; the ciphertext is assembled before the definite-length encryptedContent is emitted, byte-for-byte the buffered form. `decrypt(input, keyMaterial, opts)` recovers the content through the matching arm and returns it with an `authenticated` flag; every secret-dependent failure collapses to one uniform `cms/decrypt-failed` verdict (Bleichenbacher, EFAIL, and password-oracle freedom), and PKCS#1 v1.5 is decrypt-only under the RFC 3218 implicit-rejection countermeasure. With `opts.stream: true` the recovered `content` is an async iterable of plaintext chunks instead of a single Buffer, for a payload too large to hold whole; the authenticated modes (AuthEnvelopedData, AuthenticatedData, AES-GCM) verify integrity before the iterable yields, so a forged message throws before any plaintext is exposed, while a CBC EnvelopedData or EncryptedData yields the plaintext as the cipher produces it. Every key-establishment secret the toolkit allocates is wiped once used, on the failing path as well as the succeeding one: the KEM shared secret and its derived key-encryption key, the raw ECDH / X25519 / X448 agreement secret, a password-derived key-encryption key, and the content-encryption key itself, cleared once the message is complete since all recipients share it. Caller-supplied key material is never written to (best-effort; NIST SP 800-227 §4.2, RFC 9629 §7). `authenticate(content, recipients, opts)` produces an `id-ct-authData` (§9): cleartext content plus an HMAC-SHA-256/384/512 MAC, authenticated but not encrypted, with the fresh MAC key wrapped for every recipient through the same RecipientInfo model. The MAC covers the authenticated attributes (content-type and message-digest) re-tagged to the EXPLICIT SET OF (§9.2), or the content octets directly; `decrypt` recovers the MAC key, recomputes the MAC and independently the message-digest (§9.3), and releases the content only after both pass, with every secret-dependent failure collapsing to the uniform `cms/decrypt-failed`. `compress(content, opts)` and `decompress(input, opts)` produce and consume a CompressedData (RFC 3274; ZLIB, version 0, id-alg-zlibCompress); decompress bounds the uncompressed output at 16 MiB and stops before it is materialized, so a decompression bomb fails closed as `cms/decompress-too-large`. Compression is a size transform with no integrity or confidentiality (RFC 8551 §2.4.5). `certsOnly(certs, opts?)` builds a certs-only certificate-management message (RFC 8551 §3.8): a degenerate SignedData with an empty signerInfos and no eContent that conveys certificates and CRLs without signing anything, `parseCertsOnly(input, opts?)` reads one back to its raw certificate and CRL DER (a CRL-only message is valid here, unlike the cert-required RFC 5272 form that `pki.est.parseCertsOnly` reads), and `isCertsOnly(input)` recognizes one structurally. Fail-closed with typed `cms/*` errors — `sign`, `verify`, `countersign`, `encrypt`, `authenticate`, `decrypt`, `compress`, `decompress`, `certsOnly`, `parseCertsOnly`, `isCertsOnly` |
243
243
  | `pki.smime` | S/MIME message assembly, verification, encryption, and compression over the CMS layer (RFC 8551). `sign(content, signers, opts)` wraps a MIME entity in either form: `multipart/signed`, where the content stays readable in any MUA and a detached CMS SignedData rides alongside as `application/pkcs7-signature` with a matching `micalg`, or `application/pkcs7-mime; smime-type=signed-data`, where the whole entity is a base64 CMS SignedData. The signed bytes are the entity's §3.1.1 canonical form with CRLF line endings, and `verify(message, opts)` unwraps both forms and recomputes over the same canonicalizer, so a transport that re-wraps line endings still verifies while a tampered part fails. `encrypt(content, recipients, opts)` envelopes a MIME entity as an opaque `application/pkcs7-mime` message and `decrypt(message, keyMaterial, opts)` opens one, as `smime-type=authEnveloped-data` (AES-GCM, confidentiality and integrity, the default) or `smime-type=enveloped-data` (AES-CBC, confidentiality only, so `decrypt` reports `authenticated: false`, the §3.3 no-integrity caveat). The `smime-type` is derived from the CMS body rather than the header, and decryption is fail-closed and oracle-free. The crypto is entirely `pki.cms.sign` / `verify` / `encrypt` / `decrypt`, so it is algorithm-agnostic: any RSA / RSASSA-PSS / ECDSA / EdDSA / ML-DSA / SLH-DSA signer and any RSA-OAEP / ECDH / X25519 / X448 / AES-KW / PBKDF2 / ML-KEM recipient carries through. As with `cms.verify`, `verify` returns the per-signer verdict plus the recovered content, and `valid` and `trusted` are separate claims: `valid` says the signature is sound under a certificate the message carried, `trusted` says every signer chained to a root named in `opts.trustAnchors`. Anchoring here is validated for email at both ends of the chain — the signer certificate must carry `emailProtection` (RFC 8551 §4.4.4) and the anchor's own trust metadata must permit that purpose, since a root can be distrusted for email while remaining a good TLS root. Override either with `requiredEku` / `checkPurpose`. `compress(content, opts)` and `decompress(message, opts)` add the opaque `application/pkcs7-mime; smime-type=compressed-data; name=smime.p7z` frame (§3.6, RFC 3274), a size transform with no integrity or confidentiality (§2.4.5), bounded against a bomb; the recovered content, which may itself be signed or enveloped, is returned for the caller to re-verify. Header protection (RFC 9788): `sign` and `encrypt` take `opts.protectHeaders`, which inlines the caller's `opts.headers` on the Cryptographic Payload root (its Content-Type gaining `hp="clear"` when signed or `hp="cipher"` when encrypted) so the CMS signature or encryption covers them, defeating a transport that rewrites or reads Subject, From, and the rest. `verify` and `decrypt` surface the authenticated inner set as `protectedHeaders` plus `headerProtection { present, mode, fromMismatch, confidential, legacy }`, so a tampered outer header cannot alter it and `fromMismatch` flags an outer From that disagrees. Encryption applies a Header Confidentiality Policy: the default `hcp_baseline` obscures the outer Subject to `[...]` and removes Comments and Keywords, so the real values live only in the ciphertext, and `decrypt` recovers them. Every emitted header routes through a fail-closed injection guard that rejects a CR, LF, or NUL value and a non-ftext name, and a malformed or contradictory `hp` wrap fails closed as `smime/bad-header-protection` rather than silently downgrading. The CMS crypto is unchanged. Inbound legacy RFC 8551 header protection is recognized opt-in: `verify` and `decrypt` with `opts.legacyHeaderProtection` detect a legacy `message/rfc822`-wrapped payload by the RFC 9788 §4.10.1 four-condition identification and surface the inner headers under `headerProtection.legacy = { headers, mode, fromMismatch, confidential }`, where `headers` is an ordered `[{ name, value }]` array retaining legally repeated fields such as `Received`. Those never appear in `protectedHeaders` and never set `present: true`. Because a legacy message is structurally indistinguishable from an ordinary forwarded `message/rfc822`, this is an explicit heuristic (§4.10.2, "no strong end-to-end guarantees"): a caller keying trust off `present` or `protectedHeaders` is never misled, and only one that explicitly reads `headerProtection.legacy.headers` and cross-checks `legacy.fromMismatch` consumes it. It is off by default, and a nested crypto layer, an inner `hp=`, a non-`message/rfc822` payload, or a duplicate Content-Type reports `legacy: null`. Bidirectionally interoperable with `openssl smime` and `openssl cms`. `buildCertsOnly(certs, opts?)` wraps a `pki.cms.certsOnly` certificate-management message in one `application/pkcs7-mime; smime-type=certs-only; name=smime.p7c` entity, read back by OpenSSL's `pkcs7 -print_certs`. Fail-closed with typed `smime/*` errors — `sign`, `verify`, `encrypt`, `decrypt`, `compress`, `decompress`, `buildCertsOnly` |
244
244
  | `pki.tsp` | Time-Stamp Protocol (RFC 3161). `sign(messageImprint, tsa, opts)` produces a TimeStampToken: a CMS SignedData over `pki.cms.sign` whose content is a `TSTInfo` carrying the timestamped message imprint, the TSA policy, a serial number, and `genTime` with optional accuracy, nonce, and ordering, plus the §2.4.2 signing-certificate attribute binding the token to the TSA certificate (SHA-2 imprints, any `pki.cms.sign` TSA key). The TSA certificate is held to §2.3 before signing (one critical extendedKeyUsage naming timeStamping alone) with the codes `verify` answers, `genTime` keeps its milliseconds as the §2.4.2 fraction of a second, and an accuracy naming no field is refused. `request` and `parseRequest` build and parse the TimeStampReq a client sends (imprint, requested policy, nonce, certReq); `response` and `parseResponse` handle the TimeStampResp a TSA returns, either a granted status wrapping a token or a rejection with PKIStatus and failure info, with the §2.4.2 status-to-token coupling enforced in both directions. `verify(token, data, opts)` verifies a token fail-closed: the CMS signature over the exact signed bytes, the message imprint recomputed from the data, the TSTInfo content type, the ESSCertID(V2) binding to the TSA certificate, the §2.3 critical timeStamping-only extendedKeyUsage, the request nonce when used, and, with a trust anchor supplied, full certification-path validation of the TSA certificate at the token's `genTime` — judged under the `timeStamping` purpose, so an anchor's own per-purpose trust metadata reaches the decision rather than sitting inert. It returns `{ valid, trusted, genTime, serialNumber, tstInfo, ... }`, where `trusted` is the separate claim that the authority chained to an anchor you named: without one there is nothing to chain to and it is `false`, which is the distinction a timestamp re-read years later turns on — `sign`, `request`, `parseRequest`, `response`, `parseResponse`, `verify` |
package/lib/constants.js CHANGED
@@ -143,6 +143,7 @@ var LIMITS = Object.assign(Object.create(null), {
143
143
  PATH_AIA_MAX_RESPONSE_BYTES: BYTES.mib(1),
144
144
  PATH_AIA_MAX_CERTS_PER_RESPONSE: 16,
145
145
  PKCS12_MAX_ELEMENTS: 1024,
146
+ PKCS12_MAX_DH_PAIRS: 8,
146
147
  PKCS12_MAX_REDECODES: 64,
147
148
  PKCS12_MAX_BAG_DEPTH: 16,
148
149
  BER_MAX_STRING_NESTING: 8,
@@ -238,6 +239,11 @@ var NAMES = Object.assign(Object.create(null), {
238
239
  "SLH-DSA-SHA2-128s": "SLH-DSA-SHA2-128s", "SLH-DSA-SHA2-128f": "SLH-DSA-SHA2-128f",
239
240
  "SLH-DSA-SHA2-192s": "SLH-DSA-SHA2-192s", "SLH-DSA-SHA2-256s": "SLH-DSA-SHA2-256s",
240
241
  },
242
+ /** @internal The output length in octets of each fixed-length digest, by the OID registry's name
243
+ * (FIPS 180-4, FIPS 202). A structure that carries "the hash of X under algorithm A" is held to
244
+ * this length: an OCSP CertID's issuer hashes, a timestamp's messageImprint. The XOFs (SHAKE) have
245
+ * no single length and are absent. */
246
+ DIGEST_OCTETS: { sha1: 20, sha256: 32, sha384: 48, sha512: 64, "sha3-256": 32, "sha3-512": 64 },
241
247
  });
242
248
 
243
249
  /** @internal Each inner table is looked up by a name a certificate supplies, so it answers from
package/lib/crmf-sign.js CHANGED
@@ -25,7 +25,6 @@ var _createHmac = nodeCrypto.createHmac;
25
25
  var _diffieHellman = nodeCrypto.diffieHellman;
26
26
  var _createPublicKey = nodeCrypto.createPublicKey;
27
27
  var _createPrivateKey = nodeCrypto.createPrivateKey;
28
- var _checkPrimeSync = nodeCrypto.checkPrimeSync;
29
28
  var asn1 = require("./asn1-der");
30
29
  var oid = require("./oid");
31
30
  var x509 = require("./schema-x509");
@@ -445,30 +444,17 @@ function _assertAgreementExponent(parts, what) {
445
444
  }
446
445
  }
447
446
 
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. */
447
+ /** @internal Whether a stated order and cofactor describe the p and g stated beside them: the key
448
+ * module's tests, a comparison, a multiplication and a modulo, which every path that reads these
449
+ * parameters can afford. The archival arm reads a key without bounding its size, and the tests it
450
+ * leaves to the certifying authority are the ones whose cost grows with it, a modular exponentiation
451
+ * and two primality proofs. */
454
452
  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
- }
453
+ key.assertDhDomainCoherent(p, g, q, j, CrmfError, "crmf/bad-popo", what);
464
454
  }
465
455
 
466
456
  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
- }
457
+ key.assertDhOperandsWithin([p, g, y, q, j], CrmfError, "crmf/bad-popo", what);
472
458
  _assertDhParamsCoherent(p, g, q, j, what);
473
459
  /** @internal A PrivateKeyInfo states the group without stating a public value in it, so the two
474
460
  * tests that hold a value to these parameters have nothing to run against and the rest still do.
@@ -481,12 +467,8 @@ function _assertDhGroup(p, g, y, q, j, forAgreement, what) {
481
467
  * cost seconds on a large modulus and this one costs a modular exponentiation, so a set of
482
468
  * parameters that cannot be a group is turned away at the cheaper of the two. The rest of that
483
469
  * 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
- }
470
+ if (q !== null) key.assertDhGeneratorOrder(p, g, q, CrmfError, "crmf/bad-popo", what);
471
+ key.assertDhModulusPrime(p, CrmfError, "crmf/bad-popo", what);
490
472
  /** @internal With no stated subgroup order there is nothing to test y against, so the group itself
491
473
  * has to be one whose only small orders the range above already excluded. That is a safe prime:
492
474
  * 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
@@ -503,16 +485,12 @@ function _assertDhGroup(p, g, y, q, j, forAgreement, what) {
503
485
  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
486
  }
505
487
  } 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
- }
488
+ key.assertDhOrderPrime(q, CrmfError, "crmf/bad-popo", what);
509
489
  order = q;
510
490
  /** @internal The public value has to lie in the subgroup the parameters name. This is what the
511
491
  * stated order says about the key, so it is checked wherever the parameters are read and not
512
492
  * 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
- }
493
+ if (y !== null) key.assertDhValueInSubgroup(p, q, y, CrmfError, "crmf/bad-popo", what);
516
494
  }
517
495
  /** @internal Everything above answers whether the parameters describe the key they carry, which is
518
496
  * asked of any key this reads. What follows is the strength the AGREEMENT needs, and a key being
@@ -602,50 +580,13 @@ function _spkiParts(spkiBytes) {
602
580
  }
603
581
 
604
582
  /** @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. */
583
+ * the key is not in that form: the key module's reader, which is the only thing that looks at these
584
+ * bytes before the request travels under a MAC covering them, with this module's errors. A structure
585
+ * this module's own outer reader does not recognize as a key is not in that form either. */
607
586
  function _pkcs3Params(spkiBytes, what) {
608
587
  var parts = _spkiParts(spkiBytes);
609
588
  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
- }
589
+ return key.pkcs3Params(spkiBytes, CrmfError, "crmf/bad-popo", what);
649
590
  }
650
591
 
651
592
  /** @internal A container is read for the tag it carries and not for merely having children: a
@@ -654,61 +595,14 @@ function _pkcs3Params(spkiBytes, what) {
654
595
  * key nothing else can read. The predicate itself is the engine's. */
655
596
  var _isUniversal = schema.isUniversal;
656
597
 
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. */
598
+ /** @internal The p, g, q and cofactor an X9.42 DomainParameters states, read by the key module,
599
+ * which owns the structure and the conversion that drops its last three fields; the errors are this
600
+ * module's. Both halves of a finite-field key carry this structure and both take that conversion,
601
+ * so both read it in that one place. */
679
602
  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;
603
+ return key.x942Domain(paramsNode, CrmfError, "crmf/bad-popo", what);
709
604
  }
710
605
 
711
- /** @internal One past the largest Diffie-Hellman operand this module computes with, built once. */
712
606
  /** @internal Two raised to a count of BITS, so a bound states the width it is named for: a value is
713
607
  * at least n bits wide exactly when it is not below 2^(n-1), and at most n bits wide exactly when it
714
608
  * is below 2^n. Counting in bytes and shifting by eight per byte lands a whole byte short of that. */
@@ -718,56 +612,17 @@ function _pow2(bits) {
718
612
  return v;
719
613
  }
720
614
 
721
- var _DH_MAX = _pow2(8 * constants.LIMITS.DH_MAX_MODULUS_BYTES);
722
-
723
615
  /** @internal The smallest modulus a group may be agreed in, and the smallest order a q may name. */
724
616
  var _DH_MIN_P = _pow2(8 * constants.LIMITS.DH_MIN_MODULUS_BYTES - 1);
725
617
  var _DH_MIN_Q = _pow2(8 * constants.LIMITS.DH_MIN_SUBGROUP_BYTES - 1);
726
618
 
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
- }
619
+ /** @internal Whether a value is prime: the key module's test, remembered there across calls, since
620
+ * an enrollment run asks the same question of the same group every time. */
621
+ var _isPrime = key.isPrime;
748
622
 
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
- }
623
+ /** @internal b^e mod m, the key module's. The exponent is a public domain parameter and the base a
624
+ * public key, so no operand here is secret and the loop is not written to hide one. */
625
+ var _modPow = key.modPow;
771
626
 
772
627
  /** @internal An X.509 Diffie-Hellman certificate names dhpublicnumber and carries X9.42
773
628
  * DomainParameters (RFC 3279 sec. 2.3.3), where this runtime classifies only the PKCS#3 DHParameter
package/lib/key.js CHANGED
@@ -21,10 +21,12 @@
21
21
 
22
22
  var nodeCrypto = require("crypto");
23
23
  var asn1 = require("./asn1-der");
24
+ var constants = require("./constants");
24
25
  var oid = require("./oid");
25
26
  var pbes2 = require("./pbes2");
26
27
  var pkcs8 = require("./schema-pkcs8");
27
28
  var pkix = require("./schema-pkix");
29
+ var schema = require("./schema-engine");
28
30
  var webcrypto = require("./webcrypto");
29
31
  var compositeKem = require("./composite-kem");
30
32
  var frameworkError = require("./framework-error");
@@ -32,6 +34,7 @@ var guard = require("./guard-all");
32
34
  var intrinsic = require("./guard-intrinsic");
33
35
  var _assign = intrinsic.assign;
34
36
  var _create = intrinsic.create;
37
+ var _keyEquals = intrinsic.uncurry(nodeCrypto.KeyObject.prototype.equals);
35
38
  var _isArray = intrinsic.isArray;
36
39
  var _bufferFrom = intrinsic.bufferFrom;
37
40
  var _floor = intrinsic.floor;
@@ -349,20 +352,376 @@ var _PUBLIC_FROM_PRIVATE_OPTS = _assign(_create(null), { pem: 1 });
349
352
  * from the AlgorithmIdentifier alone: a key that is not well formed enough to state one is left to the
350
353
  * decoder below, which reports it. */
351
354
  function _compositeKemOidOf(der) {
355
+ var algOid = _algorithmOidAt(der, 1);
356
+ return algOid !== null && compositeKem.isCompositeKem(algOid) ? algOid : null;
357
+ }
358
+
359
+ /** @internal The AlgorithmIdentifier OID a key structure names, read without the structure's strict
360
+ * rules: `at` 1 for a OneAsymmetricKey (version first), 0 for a SubjectPublicKeyInfo. A structure that
361
+ * cannot state one yields null and is left to the decoder that reports it. Reading loosely matters for
362
+ * a composite key: one that breaks a OneAsymmetricKey rule is still a composite key, and the module
363
+ * that owns the algorithm is the one that should say so, since the runtime decoder would report that
364
+ * it cannot read the key rather than that the parameters are not allowed (draft sec. 5.3). */
365
+ function _algorithmOidAt(der, at) {
352
366
  var algOid;
353
367
  try {
354
- /** @internal The AlgorithmIdentifier OID only, read without the strict OneAsymmetricKey rules. A
355
- * composite key that breaks one of those rules is still a composite key, and the module that owns
356
- * the algorithm is the one that should say so: parsing strictly here would send a composite key
357
- * carrying parameters to the runtime decoder, which reports that it cannot read the key rather
358
- * than that the parameters are not allowed (draft sec. 5.3). */
359
368
  var node = asn1.decode(der);
360
- if (!node.children || node.children.length < 3) return null;
361
- var alg = node.children[1];
369
+ if (!node.children || node.children.length <= at) return null;
370
+ var alg = node.children[at];
362
371
  if (!alg.children || alg.children.length < 1) return null;
363
372
  algOid = asn1.read.oid(alg.children[0]);
364
- } catch (_e) { return null; }
365
- return typeof algOid === "string" && compositeKem.isCompositeKem(algOid) ? algOid : null;
373
+ } catch (_e) { return null; } // allow:swallow-unverified a structure that states no algorithm is refused by the decoder it stands before
374
+ return typeof algOid === "string" ? algOid : null;
375
+ }
376
+
377
+ var _OID_DH_X942 = oid.byName("dhpublicnumber");
378
+ var _OID_DH_PKCS3 = oid.byName("dhKeyAgreement");
379
+ var _isUniversal = schema.isUniversal;
380
+
381
+ /** @internal Whether an algorithm identifier names a finite-field Diffie-Hellman key in either of
382
+ * its encodings. */
383
+ function _isDhOid(algOid) {
384
+ return algOid === _OID_DH_X942 || algOid === _OID_DH_PKCS3;
385
+ }
386
+
387
+ /** @internal ValidationParms is SEQUENCE { seed BIT STRING, pgenCounter INTEGER } (RFC 3279
388
+ * sec. 2.3.3). The conversion drops it, so reading it is the only thing that answers for it: a key
389
+ * whose parameters do not hold the two fields is malformed rather than merely carrying something the
390
+ * conversion does not need, and the counter is the count of a generation procedure, so a negative
391
+ * one is malformed too. */
392
+ function _validationParms(node, ErrorClass, code, what) {
393
+ var kids = node.children;
394
+ if (!_isUniversal(node, 16) || !kids || kids.length !== 2 ||
395
+ !_isUniversal(kids[0], 3) || !_isUniversal(kids[1], 2)) {
396
+ throw new ErrorClass(code, what + " X9.42 validationParms is not a seed BIT STRING with a pgenCounter INTEGER");
397
+ }
398
+ asn1.read.bitString(kids[0]);
399
+ if (asn1.read.integer(kids[1]) < 0n) {
400
+ throw new ErrorClass(code, what + " X9.42 validationParms states a negative pgenCounter");
401
+ }
402
+ }
403
+
404
+ /** @internal The p, g, q and cofactor an X9.42 DomainParameters states. DomainParameters is
405
+ * SEQUENCE { p, g, q, j OPTIONAL, validationParms OPTIONAL } (RFC 3279 sec. 2.3.3), and the PKCS #3
406
+ * form the runtime classifies carries none of the last three, so every field is read HERE, before
407
+ * the conversion that drops it. Both halves of a finite-field key carry this structure and both take
408
+ * that conversion, so both read it in this one place: a field read on one side and skipped on the
409
+ * other is a key refused in the encoding it was handed and admitted in the one it was rewritten
410
+ * into. The algorithm named dhpublicnumber, so these bytes are DomainParameters or the key is
411
+ * malformed; there is no third reading that would let a shape this does not recognize travel on.
412
+ * Errors are the caller's: `new ErrorClass(code, message)`, the message led by `what`. */
413
+ function x942Domain(paramsNode, ErrorClass, code, what) {
414
+ var domain = asn1.decode(paramsNode.bytes);
415
+ if (!_isUniversal(domain, 16) || !domain.children ||
416
+ domain.children.length < 3 || domain.children.length > 5) {
417
+ throw new ErrorClass(code, what + " X9.42 domain parameters are not a DomainParameters SEQUENCE of p, g and q with at most two optional fields after them");
418
+ }
419
+ var out = {
420
+ p: asn1.read.integer(domain.children[0]),
421
+ g: asn1.read.integer(domain.children[1]),
422
+ q: asn1.read.integer(domain.children[2]),
423
+ j: null,
424
+ };
425
+ /** @internal j and validationParms are independently optional, so a fourth field is told apart by
426
+ * its tag rather than by its position: an INTEGER is the cofactor and a SEQUENCE is the validation
427
+ * parameters, which may appear with no cofactor before them. */
428
+ if (domain.children.length >= 4) {
429
+ var opt = domain.children[3];
430
+ if (_isUniversal(opt, 2)) {
431
+ out.j = asn1.read.integer(opt);
432
+ if (domain.children.length === 5) _validationParms(domain.children[4], ErrorClass, code, what);
433
+ } else if (_isUniversal(opt, 16)) {
434
+ if (domain.children.length === 5) {
435
+ throw new ErrorClass(code, what + " X9.42 domain parameters carry a field after validationParms");
436
+ }
437
+ _validationParms(opt, ErrorClass, code, what);
438
+ } else {
439
+ throw new ErrorClass(code, what + " X9.42 domain parameters carry a fourth field that is neither a cofactor nor validationParms");
440
+ }
441
+ }
442
+ return out;
443
+ }
444
+
445
+ /** @internal One past the largest Diffie-Hellman operand the toolkit computes with: the largest group
446
+ * it agrees over. Built once, as two raised to a count of BITS, so the bound states the width it is
447
+ * named for. */
448
+ var _DH_MAX = (function () {
449
+ var v = 1n;
450
+ for (var i = 0; i < 8 * constants.LIMITS.DH_MAX_MODULUS_BYTES; i++) v <<= 1n;
451
+ return v;
452
+ }());
453
+
454
+ /** @internal Whether every Diffie-Hellman operand in `values` (a null is an absent one) is below the
455
+ * largest group the toolkit agrees over. The tests whose cost grows with the operands, a modular
456
+ * exponentiation and a primality proof, run only after this has answered; a path that reads a key
457
+ * without bounding its size, such as one that archives rather than agrees, does not ask it. Errors
458
+ * are the caller's, as in `x942Domain`. */
459
+ function assertDhOperandsWithin(values, ErrorClass, code, what) {
460
+ for (var i = 0; i < values.length; i++) {
461
+ if (values[i] !== null && values[i] >= _DH_MAX) {
462
+ throw new ErrorClass(code, what + " parameters are larger than any Diffie-Hellman group this toolkit agrees over (" +
463
+ constants.LIMITS.DH_MAX_MODULUS_BYTES + " bytes)");
464
+ }
465
+ }
466
+ }
467
+
468
+ /** @internal base to the power exp, modulo mod, by square-and-multiply on BigInts. */
469
+ function modPow(base, exp, mod) {
470
+ var result = 1n, b = base % mod, e = exp;
471
+ while (e > 0n) {
472
+ if (e & 1n) result = (result * b) % mod;
473
+ e >>= 1n;
474
+ b = (b * b) % mod;
475
+ }
476
+ return result;
477
+ }
478
+
479
+ /** @internal Whether a stated order is one g has: g raised to q is 1 modulo p, which says the order
480
+ * of g divides q. This is one modular exponentiation, so it is asked only of operands already bounded
481
+ * by `assertDhOperandsWithin`, and after `assertDhDomainCoherent` has answered the cheaper questions.
482
+ * Whether q IS the order rather than a multiple of it is `assertDhOrderPrime`. Errors are the
483
+ * caller's. */
484
+ function assertDhGeneratorOrder(p, g, q, ErrorClass, code, what) {
485
+ if (modPow(g, q, p) !== 1n) {
486
+ throw new ErrorClass(code, what + " X9.42 domain parameters state a subgroup order its own p and g do not have");
487
+ }
488
+ }
489
+
490
+ /** @internal Whether a value is prime, by the runtime's test, remembered across calls. Proving a
491
+ * 4096-bit modulus prime costs seconds, and the question is asked of the same group every time:
492
+ * a certifying authority's parameters do not change between the keys it issues, and an enrollment
493
+ * run asks it of the same group per request. What is remembered is a fact about a number rather
494
+ * than anything a caller supplied, so a hit is the same answer the test would give. The map is
495
+ * capped and cleared wholesale when it fills, which bounds it without giving a caller a way to
496
+ * decide what stays. Asked only of operands already bounded by `assertDhOperandsWithin`. */
497
+ var _PRIME_MEMO = new intrinsic.Map();
498
+ var _PRIME_MEMO_N = 0;
499
+ var _checkPrimeSync = nodeCrypto.checkPrimeSync;
500
+
501
+ function isPrime(n) {
502
+ var hit = intrinsic.mapGet(_PRIME_MEMO, n);
503
+ if (hit !== undefined) return hit;
504
+ var answer = _checkPrimeSync(_bigToBuf(n));
505
+ if (_PRIME_MEMO_N >= constants.LIMITS.DH_PRIME_MEMO_ENTRIES) {
506
+ _PRIME_MEMO = new intrinsic.Map();
507
+ _PRIME_MEMO_N = 0;
508
+ }
509
+ intrinsic.mapSet(_PRIME_MEMO, n, answer);
510
+ _PRIME_MEMO_N++;
511
+ return answer;
512
+ }
513
+
514
+ /** @internal A non-negative BigInt as the big-endian bytes the runtime's primality test reads. */
515
+ function _bigToBuf(n) {
516
+ var len = 0, v = n;
517
+ while (v > 0n) { len++; v >>= 8n; }
518
+ if (len === 0) len = 1;
519
+ var buf = intrinsic.bufferAlloc(len);
520
+ v = n;
521
+ for (var i = len - 1; i >= 0; i--) { buf[i] = intrinsic.Number(v & 0xffn); v >>= 8n; }
522
+ return buf;
523
+ }
524
+
525
+ /** @internal Whether a Diffie-Hellman modulus is prime; a composite one describes no group. */
526
+ function assertDhModulusPrime(p, ErrorClass, code, what) {
527
+ if (!isPrime(p)) {
528
+ throw new ErrorClass(code, what + " Diffie-Hellman modulus is not prime, so the group its parameters describe does not exist");
529
+ }
530
+ }
531
+
532
+ /** @internal Whether a public value lies in the subgroup its parameters state: y raised to q is 1
533
+ * modulo p. A value outside it agrees a secret that exposes the private exponent of whichever side
534
+ * agrees, modulo the small order the value does have. One modular exponentiation, asked of bounded
535
+ * operands after the order itself was proven. Errors are the caller's. */
536
+ function assertDhValueInSubgroup(p, q, y, ErrorClass, code, what) {
537
+ if (modPow(y, q, p) !== 1n) {
538
+ throw new ErrorClass(code, 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");
539
+ }
540
+ }
541
+
542
+ /** @internal Whether a stated subgroup order is prime. `assertDhGeneratorOrder` proved the order of
543
+ * g divides q; only a prime q makes that order exactly q, so a q that is a multiple of the order
544
+ * (p-1 beside a g of order (p-1)/2 satisfies g^q = 1) names a subgroup the key need not have. */
545
+ function assertDhOrderPrime(q, ErrorClass, code, what) {
546
+ if (!isPrime(q)) {
547
+ throw new ErrorClass(code, what + " X9.42 domain parameters state a subgroup order that is not prime, so a public value in it need not have that order");
548
+ }
549
+ }
550
+
551
+ /** @internal Whether a stated order and cofactor describe the p and g stated beside them. These are
552
+ * the tests that answer that question with a comparison, a multiplication and a modulo, so their cost
553
+ * grows gently with the modulus and every path that reads these parameters can afford them, bounded
554
+ * or not; the tests whose cost grows with the modulus, a modular exponentiation and two primality
555
+ * proofs, are asked separately of bounded operands. A cofactor states (p-1)/q, so a cofactor with no
556
+ * order beside it states nothing. Errors are the caller's, as in `x942Domain`. */
557
+ function assertDhDomainCoherent(p, g, q, j, ErrorClass, code, what) {
558
+ if (p <= 2n || g <= 1n || g >= p - 1n) {
559
+ throw new ErrorClass(code, what + " parameters are not a Diffie-Hellman group");
560
+ }
561
+ /** @internal Each operand's sign is decided before the multiplication and the modulo that take it:
562
+ * a bound on these is an upper one, and a negative order or cofactor of any width would otherwise
563
+ * be multiplied before it is refused. */
564
+ if (j !== null && (q === null || j <= 0n || q <= 0n || j * q !== p - 1n)) {
565
+ throw new ErrorClass(code, what + " X9.42 cofactor does not match its own p and q");
566
+ }
567
+ if (q !== null && (q <= 1n || (p - 1n) % q !== 0n)) {
568
+ throw new ErrorClass(code, what + " X9.42 domain parameters state a subgroup order its own p and g do not have");
569
+ }
570
+ }
571
+
572
+ /** @internal The p and g a PKCS #3 DHParameter states, read strictly. DHParameter is SEQUENCE
573
+ * { prime, base, privateValueLength OPTIONAL } (PKCS #3 sec. 9); the one optional field is an
574
+ * INTEGER stating how many bits the private value has, so it is a positive count no longer than the
575
+ * modulus's own bit count, which the encoded size bounds before anything is shifted by it, since
576
+ * the codec admits an INTEGER at any width and a caller that archives a key does not bound its
577
+ * modulus. Errors are the caller's, as in `x942Domain`. */
578
+ function _dhParameter(paramsNode, ErrorClass, code, what) {
579
+ var prm = asn1.decode(paramsNode.bytes);
580
+ if (!_isUniversal(prm, 16) || !prm.children || prm.children.length < 2 || prm.children.length > 3) {
581
+ throw new ErrorClass(code, what + " PKCS#3 Diffie-Hellman parameters are not a DHParameter SEQUENCE");
582
+ }
583
+ var p = asn1.read.integer(prm.children[0]);
584
+ if (prm.children.length === 3) {
585
+ if (!_isUniversal(prm.children[2], 2)) {
586
+ throw new ErrorClass(code, what + " PKCS#3 privateValueLength is not an INTEGER");
587
+ }
588
+ var pvl = asn1.read.integer(prm.children[2]);
589
+ if (pvl <= 0n) {
590
+ throw new ErrorClass(code, what + " PKCS#3 privateValueLength is not a positive length");
591
+ }
592
+ if (pvl > intrinsic.BigInt(prm.children[0].bytes.length) * 8n || (1n << (pvl - 1n)) > p) {
593
+ throw new ErrorClass(code, what + " PKCS#3 privateValueLength states a private value longer than its own modulus, which no value in the group is");
594
+ }
595
+ }
596
+ return { p: p, g: asn1.read.integer(prm.children[1]) };
597
+ }
598
+
599
+ /** @internal The p, g and public value of a PKCS #3 dhKeyAgreement SubjectPublicKeyInfo, or null
600
+ * when the key is not in that form. The parameters state no subgroup order, so the group they
601
+ * describe is checked without one. A structure that names the algorithm and cannot be read as the
602
+ * key is refused in the caller's class. */
603
+ function pkcs3Params(spkiBytes, ErrorClass, code, what) {
604
+ if (_algorithmOidAt(spkiBytes, 0) !== _OID_DH_PKCS3) return null;
605
+ var node = asn1.decode(spkiBytes);
606
+ try {
607
+ var alg = node.children[0];
608
+ if (!alg.children || alg.children.length !== 2 || node.children.length !== 2) {
609
+ throw new ErrorClass(code, what + " PKCS#3 Diffie-Hellman key is not an AlgorithmIdentifier with parameters and a public key");
610
+ }
611
+ var dom = _dhParameter(alg.children[1], ErrorClass, code, what);
612
+ var pub = asn1.read.bitString(node.children[1]);
613
+ if (!guard.crypto.isOctetAligned(pub)) {
614
+ throw new ErrorClass(code, what + " Diffie-Hellman public key BIT STRING must be octet-aligned (0 unused bits)");
615
+ }
616
+ return { p: dom.p, g: dom.g, y: asn1.read.integer(asn1.decode(pub.bytes)) };
617
+ } catch (e) {
618
+ if (e instanceof ErrorClass) throw e;
619
+ throw new ErrorClass(code, what + " PKCS#3 Diffie-Hellman key could not be read", e);
620
+ }
621
+ }
622
+
623
+ /** @internal The p, g and private exponent of a PKCS #3 dhKeyAgreement PrivateKeyInfo, read to the
624
+ * same shape as its public half; null when the key is not in that form. */
625
+ function _pkcs3Private(der, what) {
626
+ if (_algorithmOidAt(der, 1) !== _OID_DH_PKCS3) return null;
627
+ var node = asn1.decode(der);
628
+ try {
629
+ var alg = node.children[1];
630
+ if (!alg.children || alg.children.length !== 2 || !node.children[2]) {
631
+ throw _err("key/bad-input", what + " PKCS#3 Diffie-Hellman key is not an AlgorithmIdentifier with parameters and a private key");
632
+ }
633
+ var dom = _dhParameter(alg.children[1], KeyError, "key/bad-input", what);
634
+ return { p: dom.p, g: dom.g, x: asn1.read.integer(asn1.decode(asn1.read.octetString(node.children[2]))) };
635
+ } catch (e) {
636
+ if (e instanceof KeyError) throw e;
637
+ throw _err("key/bad-input", what + " PKCS#3 Diffie-Hellman key could not be read", e);
638
+ }
639
+ }
640
+
641
+ /** @internal A Diffie-Hellman structure in the PKCS #3 form (every DH key is one by the time this
642
+ * reads it), held to the toolkit's group bound and to being a group before the runtime imports it:
643
+ * the import derives or compares a public value by modular exponentiation whose cost is the width
644
+ * of p and of the exponent, and a delivered key states any width it likes. So p, g and the value
645
+ * the structure carries (the private exponent at `at` 1, the public value at `at` 0) are capped at
646
+ * the largest group the toolkit agrees over, the cap that every other path computing in a DH group
647
+ * applies; p and g are then held to describing a group and p to being prime, whichever encoding
648
+ * the key arrived in, so a structure the X9.42 rewrite never saw answers the same questions; and a
649
+ * private exponent is held inside its group: at least 1 and below p (RFC 2631 sec. 2.2 narrows it
650
+ * to [2, q-2], which is the agreement's test). Anything that is not a DH structure is left alone. */
651
+ function _assertDhWithin(der, at, what) {
652
+ var read = at === 0 ? pkcs3Params(der, KeyError, "key/bad-input", what) : _pkcs3Private(der, what);
653
+ if (read === null) return;
654
+ var value = at === 0 ? read.y : read.x;
655
+ assertDhOperandsWithin([read.p, read.g, value], KeyError, "key/bad-input", what);
656
+ assertDhDomainCoherent(read.p, read.g, null, null, KeyError, "key/bad-input", what);
657
+ assertDhModulusPrime(read.p, KeyError, "key/bad-input", what);
658
+ if (at === 1 && (value <= 0n || value >= read.p)) {
659
+ throw _err("key/bad-input", what + " Diffie-Hellman private exponent is outside its own group");
660
+ }
661
+ if (at === 0 && (value <= 1n || value >= read.p - 1n)) {
662
+ throw _err("key/bad-input", what + " Diffie-Hellman public value is outside the group (RFC 2875 sec. 3)");
663
+ }
664
+ }
665
+
666
+ /** @internal One finite-field Diffie-Hellman key in the encoding the runtime classifies. A certificate
667
+ * names a DH key in the X9.42 form (RFC 3279 sec. 2.3.3: `dhpublicnumber` with DomainParameters
668
+ * { p, g, q, j, validationParms }), while a generated key is written in the PKCS #3 form
669
+ * (`dhKeyAgreement` with DHParameter { p, g, privateValueLength }); both carry the value itself as one
670
+ * INTEGER. The runtime reads the X9.42 form as a key of no type, which would call the two halves
671
+ * different families, so an X9.42 structure is rewritten with the PKCS #3 identifier over the same
672
+ * p, g and value. The order and cofactor the rewrite drops are read first and held to the p and g
673
+ * beside them, since the PKCS #3 form cannot carry them and nothing after this reads them: a
674
+ * DomainParameters that omits q or states one its own p contradicts is a malformed key, refused
675
+ * whatever value it carries. Anything not X9.42 is returned as given. */
676
+ function _dhAsPkcs3(der, at, what) {
677
+ if (_algorithmOidAt(der, at) !== _OID_DH_X942) return der;
678
+ var node = asn1.decode(der);
679
+ var algNode = node.children[at];
680
+ if (!algNode.children || algNode.children.length !== 2) {
681
+ throw _err("key/bad-input", what + " X9.42 AlgorithmIdentifier does not carry DomainParameters");
682
+ }
683
+ var dom = x942Domain(algNode.children[1], KeyError, "key/bad-input", what);
684
+ assertDhOperandsWithin([dom.p, dom.g, dom.q, dom.j], KeyError, "key/bad-input", what);
685
+ assertDhDomainCoherent(dom.p, dom.g, dom.q, dom.j, KeyError, "key/bad-input", what);
686
+ assertDhGeneratorOrder(dom.p, dom.g, dom.q, KeyError, "key/bad-input", what);
687
+ assertDhModulusPrime(dom.p, KeyError, "key/bad-input", what);
688
+ assertDhOrderPrime(dom.q, KeyError, "key/bad-input", what);
689
+ /** @internal The one field the X9.42 form states that the PKCS #3 form cannot be held to is the
690
+ * subgroup, so a public value is held to it here, where q is still known. */
691
+ if (at === 0) {
692
+ var pub = asn1.read.bitString(node.children[1]);
693
+ if (!guard.crypto.isOctetAligned(pub)) {
694
+ throw _err("key/bad-input", what + " Diffie-Hellman public key BIT STRING must be octet-aligned (0 unused bits)");
695
+ }
696
+ var y = asn1.read.integer(asn1.decode(pub.bytes));
697
+ if (y <= 1n || y >= dom.p - 1n) {
698
+ throw _err("key/bad-input", what + " Diffie-Hellman public value is outside the group (RFC 2875 sec. 3)");
699
+ }
700
+ assertDhValueInSubgroup(dom.p, dom.q, y, KeyError, "key/bad-input", what);
701
+ }
702
+ var alg = b.sequence([b.oid(_OID_DH_PKCS3), b.sequence([b.integer(dom.p), b.integer(dom.g)])]);
703
+ var fields = [];
704
+ for (var i = 0; i < node.children.length; i++) guard.list.append(fields, i === at ? alg : b.raw(node.children[i].bytes));
705
+ return b.sequence(fields);
706
+ }
707
+
708
+ /** @internal Whether a composite ML-KEM private key and a SubjectPublicKeyInfo are one pair: a secret
709
+ * encapsulated to the public key decapsulates under the private key to the same value only for the
710
+ * pair. The toolkit's own KEM stands in for the runtime here because the runtime cannot read the
711
+ * algorithm; every secret the probe makes is wiped on every way out. A public key of another
712
+ * algorithm, composite or not, is another family and not a pair. */
713
+ async function _compositeCorrespondsTo(privDer, spkiDer, privateOid) {
714
+ if (_algorithmOidAt(spkiDer, 0) !== privateOid) return false;
715
+ var sealed = null, opened = null;
716
+ try {
717
+ sealed = await compositeKem.encapsulate(spkiDer);
718
+ opened = await compositeKem.decapsulate(privDer, sealed.ciphertext);
719
+ return guard.crypto.constantTimeEqual(opened, sealed.sharedSecret);
720
+ } catch (e) {
721
+ throw _err("key/unsupported-algorithm", "the key pair could not be exercised to decide whether its two halves correspond", e);
722
+ } finally {
723
+ guard.secret.zeroizeAll([sealed && sealed.sharedSecret, opened], KeyError, "key/bad-input", "the correspondence probe secrets");
724
+ }
366
725
  }
367
726
 
368
727
  async function publicFromPrivate(privateKey, opts) {
@@ -399,8 +758,10 @@ async function publicFromPrivate(privateKey, opts) {
399
758
  *
400
759
  * So the pair is proven by USING it, on whichever operation the key type can perform: a signature the
401
760
  * public half verifies, a Diffie-Hellman agreement that reaches the same secret from both sides, or a
402
- * key encapsulation the private half decapsulates to the same secret. Each fails for a key that merely
403
- * claims the public half.
761
+ * key encapsulation the private half decapsulates to the same secret (the toolkit's own KEM for a
762
+ * composite ML-KEM key the runtime cannot read). Each fails for a key that merely claims the public
763
+ * half. A finite-field DH key, whose private structure carries the exponent alone, is proven by the
764
+ * value the exponent generates, in either of its two encodings (PKCS #3 or X9.42).
404
765
  *
405
766
  * What a true answer means is exactly that: the private key WORKS with this public key, on the
406
767
  * operation its type performs. It is not a statement that every field of the private structure is
@@ -499,23 +860,55 @@ function _pssSalt(a, b) {
499
860
 
500
861
  async function correspondsTo(privateKey, spkiDer) {
501
862
  var privDer = await _toPrivateKeyDer(privateKey);
863
+ var compositeOid = _compositeKemOidOf(privDer);
864
+ if (compositeOid !== null) return _compositeCorrespondsTo(privDer, _bufferFrom(spkiDer), compositeOid);
865
+ /** @internal Whether the two halves are finite-field Diffie-Hellman is answered from their
866
+ * algorithm identifiers before either structure is validated: a DH structure's validation proves
867
+ * its modulus prime, and a half of another family is not a pair with it whatever it states, so
868
+ * that proof is never run to say so. */
869
+ if (_isDhOid(_algorithmOidAt(privDer, 1)) !== _isDhOid(_algorithmOidAt(_bufferFrom(spkiDer), 0))) return false;
502
870
  var priv, pub;
503
- try { priv = nodeCrypto.createPrivateKey({ key: privDer, format: "der", type: "pkcs8" }); }
504
- catch (e) { throw _err("key/bad-input", "the private key could not be read", e); }
505
- try { pub = nodeCrypto.createPublicKey({ key: _bufferFrom(spkiDer), format: "der", type: "spki" }); }
871
+ /** @internal The PKCS #3 rewrite of an X9.42 private key is this function's own copy of the
872
+ * exponent, wiped once the runtime holds the key. */
873
+ var privAsPkcs3 = _dhAsPkcs3(privDer, 1, "the private key's");
874
+ try {
875
+ _assertDhWithin(privAsPkcs3, 1, "the private key's");
876
+ try { priv = nodeCrypto.createPrivateKey({ key: privAsPkcs3, format: "der", type: "pkcs8" }); }
877
+ catch (e) { throw _err("key/bad-input", "the private key could not be read", e); }
878
+ } finally { if (privAsPkcs3 !== privDer) guard.secret.zeroize(privAsPkcs3, KeyError, "key/bad-input", "the rewritten private key"); }
879
+ var pubAsPkcs3 = _dhAsPkcs3(_bufferFrom(spkiDer), 0, "the public key's");
880
+ _assertDhWithin(pubAsPkcs3, 0, "the public key's");
881
+ try { pub = nodeCrypto.createPublicKey({ key: pubAsPkcs3, format: "der", type: "spki" }); }
506
882
  catch (e) { throw _err("key/bad-input", "the public key could not be read", e); }
507
883
  if (!_sameKeyFamily(priv, pub)) return false;
508
884
  var kind = guard.text.keyOf(priv.asymmetricKeyType);
885
+ /** @internal Every secret a probe makes, wiped once the verdict is decided, on every way out. */
886
+ var secrets = [];
509
887
  try {
888
+ /** @internal A finite-field Diffie-Hellman PrivateKeyInfo carries the exponent alone (RFC 5958 /
889
+ * X9.42), no public copy a caller could plant, so the public value the exponent generates is a
890
+ * proof of the pair on its own; there is no signature to try and no fixed group to draw an
891
+ * ephemeral from. */
892
+ if (kind === "dh") {
893
+ /** @internal Compared as KEYS rather than as encodings: a PKCS #3 DHParameter may carry the
894
+ * optional privateValueLength beside the same p and g, and two encodings of one public value
895
+ * are one key. The runtime's equality compares the group and the value. */
896
+ return _keyEquals(nodeCrypto.createPublicKey(priv), pub) === true;
897
+ }
510
898
  if (_PAIR_KEM[kind]) {
511
899
  var sealed = nodeCrypto.encapsulate(pub);
512
- return guard.crypto.constantTimeEqual(nodeCrypto.decapsulate(priv, sealed.ciphertext), sealed.sharedKey);
900
+ guard.list.append(secrets, sealed.sharedKey);
901
+ var opened = nodeCrypto.decapsulate(priv, sealed.ciphertext);
902
+ guard.list.append(secrets, opened);
903
+ return guard.crypto.constantTimeEqual(opened, sealed.sharedKey);
513
904
  }
514
905
  if (_PAIR_AGREE[kind]) {
515
906
  var ephemeral = nodeCrypto.generateKeyPairSync(priv.asymmetricKeyType);
516
- if (!guard.crypto.constantTimeEqual(
517
- nodeCrypto.diffieHellman({ privateKey: priv, publicKey: ephemeral.publicKey }),
518
- nodeCrypto.diffieHellman({ privateKey: ephemeral.privateKey, publicKey: pub }))) return false;
907
+ var ours = nodeCrypto.diffieHellman({ privateKey: priv, publicKey: ephemeral.publicKey });
908
+ guard.list.append(secrets, ours);
909
+ var theirs = nodeCrypto.diffieHellman({ privateKey: ephemeral.privateKey, publicKey: pub });
910
+ guard.list.append(secrets, theirs);
911
+ if (!guard.crypto.constantTimeEqual(ours, theirs)) return false;
519
912
  /** @internal The agreement proves the SCALAR, not the encoding it was handed. RFC 7748 masks the
520
913
  * top bit of an X25519 u-coordinate before the ladder, so a public value differing from the real
521
914
  * one only in a masked bit reaches the same secret from both sides. The certificate would then
@@ -541,6 +934,8 @@ async function correspondsTo(privateKey, spkiDer) {
541
934
  * not be exercised without saying that the two encodings pin conflicting parameters. */
542
935
  if (e && e.code === "key/unsupported-algorithm" && e.isPkiError === true) throw e;
543
936
  throw _err("key/unsupported-algorithm", "the key pair could not be exercised to decide whether its two halves correspond", e);
937
+ } finally {
938
+ guard.secret.zeroizeAll(secrets, KeyError, "key/bad-input", "the correspondence probe secrets");
544
939
  }
545
940
  }
546
941
 
@@ -602,4 +997,15 @@ module.exports = {
602
997
  generate: generate,
603
998
  publicFromPrivate: publicFromPrivate,
604
999
  correspondsTo: correspondsTo, // @internal
1000
+ x942Domain: x942Domain, // @internal
1001
+ pkcs3Params: pkcs3Params, // @internal
1002
+ isDhOid: _isDhOid, // @internal
1003
+ assertDhOperandsWithin: assertDhOperandsWithin, // @internal
1004
+ assertDhDomainCoherent: assertDhDomainCoherent, // @internal
1005
+ assertDhGeneratorOrder: assertDhGeneratorOrder, // @internal
1006
+ assertDhModulusPrime: assertDhModulusPrime, // @internal
1007
+ assertDhOrderPrime: assertDhOrderPrime, // @internal
1008
+ assertDhValueInSubgroup: assertDhValueInSubgroup, // @internal
1009
+ isPrime: isPrime, // @internal
1010
+ modPow: modPow, // @internal
605
1011
  };
@@ -382,6 +382,92 @@ function _specForm(spec) {
382
382
  return { isObject: isObject, full: full, safeContents: full ? safeContents : null };
383
383
  }
384
384
 
385
+ /** @internal The convenience form pairs one key with one certificate, and a localKeyId pairs a key
386
+ * bag with a certificate bag (PKCS #9 sec. 5.5.2: "the local key id ... links a certificate to a
387
+ * private key"). A pair is held to being a KEY PAIR, the key's public half being the certificate's
388
+ * subjectPublicKey, since a store that links a certificate to somebody else's key is one nothing
389
+ * can use and the reader trusts the link. Bags of the full form pair across every safe. */
390
+ function _collectPairBags(bags, depth, keyBags, certBags) {
391
+ if (!intrinsic.isArray(bags)) return;
392
+ if (bags.length > C.LIMITS.PKCS12_MAX_ELEMENTS) throw _err("pkcs12/bad-input", "a SafeContents exceeds the element cap " + C.LIMITS.PKCS12_MAX_ELEMENTS);
393
+ bags = pkiBuild.reqDenseArray(bags, "bags", _err, "pkcs12/bad-input");
394
+ for (var j = 0; j < bags.length; j++) {
395
+ var bag = bags[j];
396
+ if (!bag || typeof bag !== "object") continue;
397
+ if (bag.type === "safeContents") {
398
+ if (depth + 1 <= C.LIMITS.PKCS12_MAX_BAG_DEPTH) _collectPairBags(bag.nested, depth + 1, keyBags, certBags);
399
+ continue;
400
+ }
401
+ if (bag.localKeyId == null || bag.localKeyId === "ski") continue;
402
+ if (bag.type === "key" || bag.type === "shroudedKey") guard.list.append(keyBags, bag);
403
+ else if (bag.type === "cert") guard.list.append(certBags, bag);
404
+ }
405
+ }
406
+ async function _assertKeyPairs(spec, form, safeContentsSpecs) {
407
+ var pairs = [];
408
+ if (!form.full) {
409
+ if (spec.key != null && spec.cert != null) guard.list.append(pairs, { key: spec.key, cert: spec.cert, what: "the { key, cert } pair" });
410
+ } else {
411
+ var keyBags = [], certBags = [];
412
+ for (var i = 0; i < safeContentsSpecs.length; i++) {
413
+ _collectPairBags(safeContentsSpecs[i] && safeContentsSpecs[i].bags, 0, keyBags, certBags);
414
+ }
415
+ /** @internal A localKeyId identifies ONE private key (PKCS #9 sec. 5.5.2), so the key bags are
416
+ * indexed by id and each certificate bag looks its key up: the pairing costs one probe per
417
+ * certificate bag, never the product of the two sets, and an id carried by two key bags links a
418
+ * certificate to no one key and is refused before anything is probed. The pairs a store links
419
+ * across all its safes are capped at the element cap, decided while they are collected and
420
+ * before any is probed, so the work a store can ask for is bounded by one constant rather than
421
+ * by the product of the safe cap and the per-safe element cap. */
422
+ var keyById = intrinsic.create(null);
423
+ for (var k = 0; k < keyBags.length; k++) {
424
+ var kid = intrinsic.bufToString(_bytes(keyBags[k].localKeyId, "localKeyId"), "hex");
425
+ if (keyById[kid] !== undefined) throw _err("pkcs12/bad-input", "localKeyId " + kid + " is carried by more than one key bag; a localKeyId names one private key (PKCS #9 sec. 5.5.2)");
426
+ keyById[kid] = keyBags[k];
427
+ }
428
+ for (var c = 0; c < certBags.length; c++) {
429
+ var cid = intrinsic.bufToString(_bytes(certBags[c].localKeyId, "localKeyId"), "hex");
430
+ var keyBag = keyById[cid];
431
+ if (keyBag === undefined) continue;
432
+ if (pairs.length >= C.LIMITS.PKCS12_MAX_ELEMENTS) throw _err("pkcs12/bad-input", "the store links more than " + C.LIMITS.PKCS12_MAX_ELEMENTS + " certificate bags to keys through localKeyId; the linked pairs are capped at the element cap");
433
+ guard.list.append(pairs, { key: keyBag.key, cert: certBags[c].cert, what: "the key and certificate bags sharing localKeyId " + cid });
434
+ }
435
+ }
436
+ /** @internal The correspondence is proven with the PRIVATE half (a signature, an agreement or an
437
+ * encapsulation against the certificate's key), since a PKCS#8 EC or RSA key carries public
438
+ * components of its own that a caller could plant beside private material they do not belong to.
439
+ * The key module owns the proof for every algorithm, the composite ML-KEM route included.
440
+ * Proving a finite-field Diffie-Hellman pair includes proving its group's modulus and order prime,
441
+ * about a second each at the widest group the toolkit agrees over and synchronous, so the DH
442
+ * pairs one store may link are budgeted, and the budget is decided from the keys' algorithms
443
+ * before any pair is probed. */
444
+ var halves = [], dhPairs = 0;
445
+ for (var a = 0; a < pairs.length; a++) {
446
+ var keyDer = _coerceDer(pairs[a].key, "the paired key");
447
+ var certDer = _coerceDer(pairs[a].cert, "the paired certificate");
448
+ var keyAlg, certSpki;
449
+ try { keyAlg = pkcs8.parse(keyDer).privateKeyAlgorithm.oid; }
450
+ catch (e2) { throw _err("pkcs12/bad-input", pairs[a].what + ": the key is not a well-formed PKCS#8 PrivateKeyInfo", e2); }
451
+ try { certSpki = x509.parse(certDer).subjectPublicKeyInfo; }
452
+ catch (e) { throw _err("pkcs12/bad-input", pairs[a].what + ": the certificate is not a well-formed X.509 certificate", e); }
453
+ if (key.isDhOid(keyAlg) || key.isDhOid(certSpki.algorithm.oid)) {
454
+ dhPairs++;
455
+ if (dhPairs > C.LIMITS.PKCS12_MAX_DH_PAIRS) throw _err("pkcs12/bad-input", "the store links more than " + C.LIMITS.PKCS12_MAX_DH_PAIRS + " finite-field Diffie-Hellman pairs; proving each costs a primality proof of its group, so a store is budgeted that many");
456
+ }
457
+ guard.list.append(halves, { keyDer: keyDer, certSpki: certSpki.bytes });
458
+ }
459
+ for (var p = 0; p < pairs.length; p++) {
460
+ var pairKey = halves[p].keyDer;
461
+ var pairSpki = halves[p].certSpki;
462
+ var corresponds;
463
+ try { corresponds = await key.correspondsTo(pairKey, pairSpki); }
464
+ catch (e3) { throw _err("pkcs12/bad-input", pairs[p].what + ": the key could not be held to the certificate's public key", e3); }
465
+ if (corresponds !== true) {
466
+ throw _err("pkcs12/bad-input", pairs[p].what + ": the key is not the private half of the certificate's public key; a store that links a certificate to another key is refused");
467
+ }
468
+ }
469
+ }
470
+
385
471
  function _normalizeSpec(spec, opts, form) {
386
472
  if (form.full) return form.safeContents;
387
473
  if (spec && (spec.key != null || spec.cert != null)) {
@@ -419,7 +505,13 @@ function _normalizeSpec(spec, opts, form) {
419
505
  * OpenSSL-style convenience form `{ key, cert, ca?, friendlyName?, localKeyId? }` (one PBES2-encrypted cert
420
506
  * safe plus one shrouded-key safe) or the full form `{ safeContents: [...] }`, where each element is a
421
507
  * plaintext or PBES2-encrypted `SafeContents` of key / shroudedKey / cert / crl / secret / nested
422
- * safeContents bags. Keys and certs are validated before wrapping. Password integrity (the default) MACs the
508
+ * safeContents bags. Keys and certs are validated before wrapping, and a key paired with a certificate
509
+ * (the `{ key, cert }` form, or a key bag and a certificate bag sharing a `localKeyId`, PKCS #9 sec.
510
+ * 5.5.2) must be the private half of that certificate's public key; a store linking a certificate to
511
+ * another key, or carrying one `localKeyId` on two key bags, is refused with `pkcs12/bad-input`, as is
512
+ * one linking more than 1024 certificate bags to keys, more than 8 finite-field Diffie-Hellman pairs,
513
+ * or carrying more than 1024 safes.
514
+ * Password integrity (the default) MACs the
423
515
  * AuthenticatedSafe with a classic Appendix B HMAC or an RFC 9579 PBMAC1. Public-key integrity
424
516
  * (`opts.integrity.mode: "public-key"`) instead wraps the AuthenticatedSafe in a CMS SignedData: a
425
517
  * signature from a keypair, no MacData (RFC 7292 sec. 4). Privacy (PBES2 bag encryption via `password`) is
@@ -476,6 +568,11 @@ async function _build(spec, opts) {
476
568
  if (pubKey && opts.mac != null && opts.mac !== false) throw _err("pkcs12/bad-integrity-mode", "public-key integrity has no MacData -- do not combine opts.mac with opts.integrity.mode 'public-key' (RFC 7292 sec. 4)");
477
569
  var safeContentsSpecs = _normalizeSpec(spec, opts, form);
478
570
  if (!Array.isArray(safeContentsSpecs) || !safeContentsSpecs.length) throw _err("pkcs12/bad-input", "the store has no safe contents");
571
+ /** @internal The cap the parser puts on the AuthenticatedSafe, applied before any safe is built:
572
+ * a store of more safes than the parser reads back would be encrypted in full and then refused
573
+ * by the re-parse. */
574
+ if (safeContentsSpecs.length > C.LIMITS.PKCS12_MAX_ELEMENTS) throw _err("pkcs12/bad-input", "the AuthenticatedSafe exceeds the element cap " + C.LIMITS.PKCS12_MAX_ELEMENTS + " (safeContents entries)");
575
+ await _assertKeyPairs(spec, form, safeContentsSpecs);
479
576
  var elements = [];
480
577
  for (var i = 0; i < safeContentsSpecs.length; i++) elements.push(await _buildAuthSafeElement(safeContentsSpecs[i], opts));
481
578
  var authSafeDer = b.sequence(elements);
package/lib/pki-build.js CHANGED
@@ -1256,22 +1256,6 @@ function makeBuilder(ctx) {
1256
1256
  if (!ok) throw E("bad-input", "the signing key does not correspond to the public key -- the signature would not verify");
1257
1257
  }
1258
1258
 
1259
- function samePublicKey(spkiA, spkiB) {
1260
- var a = _bufferFrom(spkiA), bb = _bufferFrom(spkiB);
1261
- if (_bufferEquals(a, bb)) return true;
1262
- var ka, kb;
1263
- // allow:swallow-unverified an SPKI the key layer cannot import matches nothing, which is the
1264
- try {
1265
- ka = nodeCrypto.createPublicKey({ key: a, format: "der", type: "spki" });
1266
- kb = nodeCrypto.createPublicKey({ key: bb, format: "der", type: "spki" });
1267
- } catch (_e) { return false; }
1268
- /** @internal Two keys of different types are never the same key, and comparing them through
1269
- * the runtime's equality leaves a fault queued in the crypto library that surfaces on the
1270
- * next unrelated key import in the process, so the type decides that case first. */
1271
- if (ka.asymmetricKeyType !== kb.asymmetricKeyType) return false;
1272
- return _keyEquals(ka, kb) === true;
1273
- }
1274
-
1275
1259
  return {
1276
1260
  E: E, code: code, KU_BIT: KU_BIT,
1277
1261
  encodeName: encodeName, isEmptyName: isEmptyName, encodeGeneralName: encodeGeneralName,
@@ -1319,4 +1303,22 @@ function skiValueOf(parsedCert) {
1319
1303
  catch (_e) { return null; } // allow:swallow-unverified -- a malformed SKI is read as absent; a signer then derives the authorityKeyIdentifier keyIdentifier from the public key, and a verifier matches on nothing
1320
1304
  }
1321
1305
 
1306
+ /** @internal Whether two SubjectPublicKeyInfo encodings carry the same public key: byte-equal, or
1307
+ * equal under the runtime's key comparison once both import. */
1308
+ function samePublicKey(spkiA, spkiB) {
1309
+ var a = _bufferFrom(spkiA), bb = _bufferFrom(spkiB);
1310
+ if (_bufferEquals(a, bb)) return true;
1311
+ var ka, kb;
1312
+ // allow:swallow-unverified an SPKI the key layer cannot import matches nothing, which is the
1313
+ try {
1314
+ ka = nodeCrypto.createPublicKey({ key: a, format: "der", type: "spki" });
1315
+ kb = nodeCrypto.createPublicKey({ key: bb, format: "der", type: "spki" });
1316
+ } catch (_e) { return false; }
1317
+ /** @internal Two keys of different types are never the same key, and comparing them through
1318
+ * the runtime's equality leaves a fault queued in the crypto library that surfaces on the
1319
+ * next unrelated key import in the process, so the type decides that case first. */
1320
+ if (ka.asymmetricKeyType !== kb.asymmetricKeyType) return false;
1321
+ return _keyEquals(ka, kb) === true;
1322
+ }
1323
+
1322
1324
  module.exports = intrinsic.freeze({ makeBuilder: makeBuilder, reqDenseArray: reqDenseArrayImpl, KU_BIT: KU_BIT, tbsNameField: tbsNameField, tbsSerialNumber: tbsSerialNumber, randomSerial: randomSerial, skiValueOf: skiValueOf, isHttpUrl: isHttpUrl, isLdapUrl: isLdapUrl });
@@ -183,9 +183,19 @@ var CERT_ID = schema.seq([
183
183
  schema.field("serialNumber", schema.integerLeaf()),
184
184
  ], {
185
185
  assert: "sequence", arity: { exact: 4 }, code: "ocsp/bad-cert-id", what: "CertID",
186
+ /** @internal RFC 6960 sec. 4.1.1: issuerNameHash and issuerKeyHash are the hashes of the issuer's
187
+ * name and key "using the hash algorithm specified in hashAlgorithm", so each is that digest's
188
+ * length; a hash of any other length names no certificate. A digest this build does not know is
189
+ * read as given, since its length is not known here. */
186
190
  build: function (m) {
191
+ var hashAlgorithm = m.fields.hashAlgorithm.value.result;
192
+ var want = constants.NAMES.DIGEST_OCTETS[hashAlgorithm.name];
193
+ if (want !== undefined) {
194
+ if (m.fields.issuerNameHash.value.length !== want) throw NS.E("ocsp/bad-cert-id", "CertID issuerNameHash is " + m.fields.issuerNameHash.value.length + " octets, not the " + want + " a " + hashAlgorithm.name + " digest is (RFC 6960 sec. 4.1.1)");
195
+ if (m.fields.issuerKeyHash.value.length !== want) throw NS.E("ocsp/bad-cert-id", "CertID issuerKeyHash is " + m.fields.issuerKeyHash.value.length + " octets, not the " + want + " a " + hashAlgorithm.name + " digest is (RFC 6960 sec. 4.1.1)");
196
+ }
187
197
  return {
188
- hashAlgorithm: m.fields.hashAlgorithm.value.result,
198
+ hashAlgorithm: hashAlgorithm,
189
199
  issuerNameHash: m.fields.issuerNameHash.value,
190
200
  issuerKeyHash: m.fields.issuerKeyHash.value,
191
201
  serialNumber: m.fields.serialNumber.value,
package/lib/tsp-sign.js CHANGED
@@ -31,6 +31,7 @@ var frameworkError = require("./framework-error");
31
31
 
32
32
  var pkix = require("./schema-pkix");
33
33
  var pkiBuild = require("./pki-build");
34
+ var constants = require("./constants");
34
35
  var TspError = frameworkError.TspError;
35
36
  var _NS = pkix.makeNS("tsp", TspError, oid);
36
37
  var b = asn1.build;
@@ -48,7 +49,7 @@ var _b = pkiBuild.makeBuilder({
48
49
  });
49
50
 
50
51
  var NODE_DIGEST = intrinsic.assign(intrinsic.create(null), { sha256: "sha256", sha384: "sha384", sha512: "sha512" });
51
- var HASH_LEN = intrinsic.assign(intrinsic.create(null), { sha256: 32, sha384: 48, sha512: 64 });
52
+ var HASH_LEN = constants.NAMES.DIGEST_OCTETS;
52
53
 
53
54
  var _REVOCATION_RANK = intrinsic.assign(intrinsic.create(null), { "false": 0, "undetermined": 1, "waived": 2, "determined": 3 });
54
55
  function _rankRevocation(v) {
@@ -422,7 +423,7 @@ function parseResponse(input) { return schemaTsp.parse(input); }
422
423
 
423
424
 
424
425
  var _VERIFY_DIGEST = intrinsic.assign(intrinsic.create(null), { sha256: "sha256", sha384: "sha384", sha512: "sha512", sha1: "sha1" });
425
- var _VERIFY_DIGEST_LEN = intrinsic.assign(intrinsic.create(null), { sha1: 20, sha256: 32, sha384: 48, sha512: 64 });
426
+ var _VERIFY_DIGEST_LEN = constants.NAMES.DIGEST_OCTETS;
426
427
  var _BIND_DIGEST = intrinsic.assign(intrinsic.create(null), { sha256: "sha256", sha384: "sha384", sha512: "sha512" });
427
428
 
428
429
  function _imprintMatches(mi, data) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blamejs/pki",
3
- "version": "0.7.38",
3
+ "version": "0.7.40",
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:c822cb0e-bdf1-4b76-ba2a-51824bba609d",
5
+ "serialNumber": "urn:uuid:19ec3e74-60d4-4102-bfdf-50fadfa1aeaa",
6
6
  "version": 1,
7
7
  "metadata": {
8
- "timestamp": "2026-09-12T14:08:23.734Z",
8
+ "timestamp": "2026-09-12T19:13:54.735Z",
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.7.38",
22
+ "bom-ref": "@blamejs/pki@0.7.40",
23
23
  "type": "application",
24
24
  "name": "pki",
25
- "version": "0.7.38",
25
+ "version": "0.7.40",
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.7.38",
29
+ "purl": "pkg:npm/%40blamejs/pki@0.7.40",
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.7.38",
57
+ "ref": "@blamejs/pki@0.7.40",
58
58
  "dependsOn": []
59
59
  }
60
60
  ]