PeculiarVentures / node-webcrypto-p11

A WebCrypto Polyfill for Node in typescript built on PKCS#11.
MIT License
44 stars 15 forks source link

Support always authenticate for private keys #73

Closed microshine closed 2 years ago

microshine commented 2 years ago

API changes

Works for ECDSA, RSASSA-PKCS1-v1_5, RSA-PSS, and RSA-OAEP algorithms

Crypto

// Adds AlwaysAuthenticateHandler to `crypto` object
// App uses returned string value for `C_Login(pin, CKU_CONTEXT_SPECIFIC)` calling imideatly after C_SignInit/C_DecryptInit functions 
crypto.onAlwaysAuthenticate = (key, container) => {
  return pin;
}

If AlwaysAuthenticateHandler returns null app skips C_Login function and PKCS#11 provider returns CKR_USER_NOT_LOGGED_IN status code

If onAlwaysAuthenticate is undefined and the private key has enabled CKA_ALWAYS_AUTHENTICATE the app throws the error on sign/decrypt operations - Crypto key requires re-authentication, but Crypto doesn't have 'onAlwaysAuthenticate' method

Generate key

const keys = await crypto.subtle.generateKey({
  name: "ECDSA",
  namedCurve: "P-256",
  alwaysAuthenticate: true, // enables CKA_ALWAYS_AUTHENTICATE for CKO_PRIVATE
 }, false, ["sign", "verify"]);

Import key

const key = await crypto.subtle.importKey(
  "pkcs8",
  pkcs8Raw,
  {
    name: "ECDSA",
    namedCurve: "P-256",
    alwaysAuthenticate: true, // enables CKA_ALWAYS_AUTHENTICATE for CKO_PRIVATE
   }, 
   false, 
   ["sign", "verify"]);

Crypto key

Private crypto key includes the alwaysAuthenticate boolean field, which represents the CKA_ALWAYS_AUTHENTICATE attribute of PKCS#11 private key

RsaCryptoKey [CryptoKey] {
  type: 'private',
  extractable: false,
  usages: [ 'sign' ],
  alwaysAuthenticate: true,
  algorithm: {
    name: 'RSASSA-PKCS1-v1_5',
    hash: { name: 'SHA-256' },
    publicExponent: Uint8Array(3) [ 1, 0, 1 ],
    modulusLength: 2048,
    label: 'RSA',
    sensitive: false,
    token: false
  },
coveralls commented 2 years ago

Coverage Status

Coverage increased (+0.6%) to 87.484% when pulling 9a6445c05549b89550ef6dd109a30a4c0cfa829c on always-auth into 462187f875414de6688e2ea3cf6ca46f2d346cba on master.