subtle crypto with ECDSA : Cannot create a key using the specified key usages

1.6k Views Asked by At

I wanted to import an ECDSA private key in Chrome to sign some data, tried yet with crypto.subtle.importKey: feeded the importKey with a derivated private key using secp256k1.

When trying to use the lib, I got stuck with the following error: Cannot create a key using the specified key usages.

The code:

const browserKey = await crypto.subtle.importKey(
    'raw',
    derivatedNode.privateKey, // ArrayBuffer
    {
        name: 'ECDSA',
        namedCurve: 'P-256' // Haven't found better fit for secp256k1?
    },
    false,
    ['sign']
);

Double-checked my private key, got Uint8Array(32) which seems to be usually OK with importKey.

Any help appreciated.

2

There are 2 best solutions below

0
On BEST ANSWER

Web Cryptography API does not support the secp256k1 curve. It will also not support it in the future.

0
On

Web Crypto API doesn't support secp256k1 but you can use two workarounds:

  1. Use a Node.js library to store the private key, and issue from the browser requests to sign some payloads: https://www.npmjs.com/package/ecdh-crypto/v/1.0.5

  2. Use ethers.js library to do it in pure Javascript, but you won't be able to have non-extractable keys, this is good if you're building a browser extension with static bundle files, otherwise you have to trust your own servers not to get compromised: https://docs.ethers.io/v4/api-wallet.html#signing