Skip to content

Instantly share code, notes, and snippets.

@michaelphipps
Created March 18, 2023 08:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save michaelphipps/ae8664a4183f14585bf94a3b91e56339 to your computer and use it in GitHub Desktop.
Save michaelphipps/ae8664a4183f14585bf94a3b91e56339 to your computer and use it in GitHub Desktop.
ECDSA how to derive public key from private key using web crypto api javascript
// Inspired/copied from : https://stackoverflow.com/questions/72151096/how-to-derive-public-key-from-private-key-using-webcryptoapi
async function getPublicKeyFromPrivateKey(privateKey) {
const jwkPrivate = await crypto.subtle.exportKey("jwk", privateKey);
delete jwkPrivate.d; // this trick makes the jwk a public key!
jwkPrivate.key_ops = ["verify"];
const publicfromprivate = await crypto.subtle.importKey("jwk", jwkPrivate, {name: "ECDSA", namedCurve: "P-256"}, true, ["verify"]);
const publicKey = await crypto.subtle.exportKey('spki', publicfromprivate);
return publicKey;
}
@michaelphipps
Copy link
Author

It's not possible to derive a public EC P-256 key directly using crypto.subtle, but you can export the private key as a JWK, then delete the private key and reimport the JWK as your EC P-256, which creates a public key from your private key! Boom!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment