PeculiarVentures / x509

@peculiar/x509 is an easy to use TypeScript/Javascript library based on @peculiar/asn1-schema that makes generating X.509 Certificates and Certificate Requests as well as validating certificate chains easy
https://peculiarventures.github.io/x509/
MIT License
86 stars 14 forks source link

X509Certificate.verify() method does not use the crypto argument #51

Closed bindon closed 1 year ago

bindon commented 1 year ago

I am experiencing the following problem

// self-signed certificate verification
const certificate = new X509Certificate(buffer);
await certificate.verify({}, new Crypto()); // => true
await certificate.verify({ publicKey: certificate.publicKey }, new Crypto()); // => false

So, as a result of checking the X509Certificate.verify() source code, it seems that the default value is used without using the parameter crypto.

if (!paramsKey) {
  // self-signed
  keyAlgorithm = { ...this.publicKey.algorithm, ...this.signatureAlgorithm };
  publicKey = await this.publicKey.export(keyAlgorithm, ["verify"], crypto);
} else if ("publicKey" in paramsKey) {
  // IPublicKeyContainer
  keyAlgorithm = { ...paramsKey.publicKey.algorithm, ...this.signatureAlgorithm };
  publicKey = await paramsKey.publicKey.export(keyAlgorithm, ["verify"]); // this
} else if (paramsKey instanceof PublicKey) {
  // PublicKey
  keyAlgorithm = { ...paramsKey.algorithm, ...this.signatureAlgorithm };
  publicKey = await paramsKey.export(keyAlgorithm, ["verify"]); // this
} else if (BufferSourceConverter.isBufferSource(paramsKey)) {
  const key = new PublicKey(paramsKey);
  keyAlgorithm = { ...key.algorithm, ...this.signatureAlgorithm };
  publicKey = await key.export(keyAlgorithm, ["verify"]); // this
} else {
  // CryptoKey
  keyAlgorithm = { ...paramsKey.algorithm, ...this.signatureAlgorithm };
  publicKey = paramsKey;
}

There is a workaround as follows, but it seems like a fix is needed.

cryptoProvider.set(new Crypto());
await certificate.verify({ publicKey: certificate.publicKey });