Derive public key from imported ECDH private key

331 Views Asked by At

I have code that imports an ECDH key like this:

const curve = await crypto.subtle.importKey(
  "pkcs8",
  keyData,
  { name: "ECDH", namedCurve: "P-256" },
  true,
  ["deriveBits"]
);

This works, however it only returns the private CryptoKey and not a whole keypair. How can I derive a public CryptoKey from the private one?

1

There are 1 best solutions below

0
On

I initially assumed this answer to another question was RSA-specific but it's not actually, the same technique works. This is the code I ended up with.

async function getPublicKey(privateKey){
  const jwk = await crypto.subtle.exportKey("jwk", privateKey)
  delete jwk.d;
  return await crypto.subtle.importKey("jwk", jwk, { name: "ECDH", namedCurve: "P-256" }, true, ["deriveBits", "deriveKey"])
}

This is kind of a kludge, if there's a better way to do this please let me know.