Skip to content

matchCertificatePrivateKey ​

matchCertificatePrivateKey ​

Check whether a certificate's subject public key belongs to a private key, returning a typed MatchCertificatePrivateKeyResult.

The Result-returning companion to certificateMatchesPrivateKey: where the boolean helper answers only "does it match?" (and throws on bad input), this surfaces the expected failures a key-intake or issuance endpoint meets on untrusted input as typed codes rather than exceptions — matching the house rule of returning Result for expected failures and throwing only for invariants. ok: true means the key owns the certificate; a failure carries one of:

  • malformed_certificate — certificate could not be parsed.
  • unsupported or limit_exceeded — certificate holds a construct micro509 does not decode or exceeds a decoding limit (see ParseCertificateErrorCode).
  • unsupported_private_key — privateKey is not an extractable private key of a supported type (from derivePublicKey).
  • key_type_mismatch — the key is a different algorithm than the certificate's subject public key.
  • key_mismatch — the key is the right algorithm but a different key.

As with certificateMatchesPrivateKey, the comparison is over exact SPKI DER, so a certificate pinning RSASSA-PSS parameters reports key_type_mismatch against the rsaEncryption SPKI WebCrypto emits.

ts
function matchCertificatePrivateKey<TMap extends ExtensionDecoderMap>(
	certificate: ParsedCertificate<TMap> | string | Uint8Array,
	privateKey: CryptoKey,
): Promise<MatchCertificatePrivateKeyResult>

Parameters

  • certificate: ParsedCertificate<TMap> | string | Uint8Array — PEM string, DER bytes, or an already-parsed certificate.
  • privateKey: CryptoKey — An extractable private CryptoKey.

Returns — A success when the key matches, or a typed failure otherwise.

See also

Examples

ts
const result = await matchCertificatePrivateKey(certificatePem, privateKey);
if (!result.ok) {
  // result.code is 'malformed_certificate' | 'unsupported_private_key'
  //              | 'key_type_mismatch' | 'key_mismatch'
  //              | 'unsupported' | 'limit_exceeded'
  throw new Error(`key does not match certificate: ${result.code}`);
}

Released under the MIT License.