PeculiarVentures / PKI.js

PKI.js is a pure JavaScript library implementing the formats that are used in PKI applications (signing, encryption, certificate requests, OCSP and TSP requests/responses). It is built on WebCrypto (Web Cryptography API) and requires no plug-ins.
http://pkijs.org
Other
1.25k stars 204 forks source link

Optionally allow engine to be passed explicitly #348

Closed gnarea closed 1 year ago

gnarea commented 2 years ago

Would you accept a PR that allowed EnvelopedData.encrypt(), EnvelopedData.decrypt(), SignedData.sign() and SignedData.verify() to take the engine as an argument, whilst still falling back to getEngine()/getCrypto() when the argument is unset?

The current approach depends on global variables:

https://github.com/PeculiarVentures/PKI.js/blob/9230ae8e2ca5af49900b5d74ba4f608b0b967f24/src/common.js#L85

... Which can be problematic for various reasons, but in this particular case I'm concerned that it limits the engine to just one: Since I'm distributing a library that uses PKI.js, I'd rather not alter the global state for third-party apps, especially if they also use PKI.js for other purposes.

microshine commented 2 years ago

I like the idea of optional argument with CryptoEngine. It makes API flexible.

We use something similar for our @peculiar/x509 project

microshine commented 2 years ago

Going to implement this feature in v3.0.0

microshine commented 2 years ago

I've published beta version of pkijs. Please try it

npm i pkijs@beta

# or

npm i pkijs@3.0.1-2

example

const cryptoEngine = new pkijs.CryptoEngine({
  name: "some",
  crypto: self.crypto,
  subtle: self.crypto.subtle,
});

const { privateKey, publicKey } = await cryptoEngine.generateKey(alg, false, ["sign", "verify"]);

await certificate.sign(privateKey, hashAlg, cryptoEngine);
gnarea commented 2 years ago

Thanks @microshine! I'll try it in my lib as soon as I can upgrade it to PKI.js v3 (see #353)