Search code examples
javascriptnode.jspem

Extract public key from private key pem using only nodejs/javascript


Using nodejs and only javascript, how do I extract a public key from a private key pem?

The private key that I have in hand is a PEM formatted private key; I'd like to extract the public key so I can distribute it to collaborators.

I regularly use the pure javascript node-forge module but have not yet discovered how to extract the public key from the private key.

I am also aware of, and presently use the ursa module to accomplish this; but I would like a pure javascript or pure nodejs solution if available.


Solution

  • from the node-forge documentation

    pem = '-----PRIVATE KEY ----- [...]'
    pki = require('node-forge').pki
    privateKey = pki.privateKeyFromPem(pem)
    publicKey  = pki.setRsaPublicKey(privateKey.n, privateKey.e)
    console.log(pki.publicKeyToPem(publicKey))