Created
March 18, 2023 08:22
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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!