WebCrypto Import ECDH JWK, Key Usage Error

72 views Asked by At

So I'm currently trying to export a ECDH private key into an Uint8Array and import it afterward. Here is my code, I'm using Google Chrome 117 on Ubuntu, unfortunately the following error keeps coming :(

Uncaught (in promise) DOMException: Cannot create a key using the specified key usages.

    str2ab(str: string) {
        const buf = new ArrayBuffer(str.length);
        const bufView = new Uint8Array(buf);
        for (let i = 0, strLen = str.length; i < strLen; i++) {
          bufView[i] = str.charCodeAt(i);
        }
        return buf;
    }

    ab2str(buf: any) {
        return String.fromCharCode.apply(null, new Uint8Array(buf));
    }

    let keyPair = await window.crypto.subtle.generateKey(
        {
            name: "ECDH",
            namedCurve: "P-384",
        },
        true,
        ["deriveKey", "deriveBits"],
    );

    const exported = await window.crypto.subtle.exportKey("jwk", keyPair.privateKey);
    const exportedKeyBuffer = str2ab(JSON.stringify(exported)));

    const privKey = await window.crypto.subtle.importKey(
      "jwk",
      JSON.parse(ab2str(exportedKeyBuffer)),
      {
        name: "ECDH",
        namedCurve: "P-384",
      },
      false,
      ["deriveKey", "deriveBits"]
    );
0

There are 0 answers