elliptic icon indicating copy to clipboard operation
elliptic copied to clipboard

How to use keys with crypto.subtle

Open DominicTobias-b1 opened this issue 3 years ago • 1 comments

Hey, thanks for the lib. I'm struggling to import a private key generated by this lib with crypto.subtle.importKey.

It accepts an ArrayBuffer for example, but I haven't been able to successfully call the function, I get the error "DOMException: The operation either timed out or was not allowed. See: https://www.w3.org/TR/webauthn-2/#sctn-privacy-considerations-client."

For example:

async function work() {
  const ec = new EC('p256')
  const keyPairEc = ec.genKeyPair()
  const priv = keyPairEc.getPrivate()
  const pub = keyPairEc.getPublic()

  console.log(priv.toArrayLike(Buffer, 'be', 32))

  const result = await crypto.subtle.importKey(
    'pkcs8',
    priv.toArrayLike(Buffer, 'be', 32).buffer, // or priv.toBuffer()
    {
      name: 'ECDSA',
      namedCurve: 'P-256',
    },
    true,
    ['sign', 'verify']
  )
  console.log({ result })
}

work()

I also tried as jwk which is successfully imported via importKey but the signed data looks different from the output of the library:

const x = pub.getX();
const y = pub.getY();
const jwkEC = {
    kty: "EC",
    key_ops: ["sign", "verify"],
    ext: true, // I see in the browser output but not in spec?
    crv: "P-256",
    x: base64url.encode(x.toArray("be")),
    y: base64url.encode(y.toArray("be")),
    d: base64url.encode(priv.toArray("be"))
  };

Any ideas what I'm doing wrong? Thanks

DominicTobias-b1 avatar Apr 01 '21 08:04 DominicTobias-b1

Hello DominicTobias-b1! Maybe the solution is no longer relevant.

const x = pk.getPublic().getX().toArrayLike(Buffer, 'be', 32).buffer;
const y = pk.getPublic().getY().toArrayLike(Buffer, 'be', 32).buffer;
const d = pk.getPrivate().toArrayLike(Buffer, 'be', 32).buffer

const jwkEC = {
    kty: "EC",
    key_ops: ["sign"],
    ext: true,
    crv: "P-256",
    x: Buffer.from(x).toString('base64url'),
    y: Buffer.from(y).toString('base64url'),
    d: Buffer.from(d).toString('base64url')
};

vovsgit avatar Jun 15 '22 13:06 vovsgit