crypto.subtle.importKey throws unspecified Error

47 Views Asked by At

I'm trying to sign a text using WEB Crypto API. I'm depending on a 3rd party to extract the certificate from a smart card, which returns a Base64 string representation of it. As far as I understand, first I need to convert it to a cryptoKey object to pass it to the sign method and that is where the error occurs. Here is how it looks in the console.

Here is what I'm doing:

  const res = await fetch("https://localhost:53952/getsigner",{
    method: "POST",
    headers: {
      'Content-type': 'application/json',
    },
    body: "{}"
  })

const body = await res.json();
const signCertString = body.chain[0];

const binaryCert = Uint8Array.from(atob(signCertString), c => c.charCodeAt(0));
const certBuffer = binaryCert.buffer;

crypto.subtle.importKey(
  "pkcs8",
  certBuffer,
  {
    name: "RSASSA-PKCS1-v1_5",
    hash: { name: "SHA-256" },
  },
  true,
  ["sign"]
)
  .then((cryptoKey) => {
    console.log("CryptoKey object created:", cryptoKey);
  })
  .catch((error) => {
    console.error("Error creating CryptoKey object:", error);
  });
1

There are 1 best solutions below

0
Alexander O'Mara On

Uint8Array.from only takes 1 argument, an array.

Uint8Array.from(atob(signCertString), c => c.charCodeAt(0))

You probably meant to do something like this, to convert your decoded string into an array of char codes:

Uint8Array.from([...atob(signCertString)].map(c => c.charCodeAt(0)))