Reputation: 328
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.
Upvotes: 17
Views: 20820
Reputation: 3641
You do not need any external packages
https://nodejs.org/api/crypto.html
const crypto = require('crypto')
const fs = require('fs')
// assuming you have a private.key file that begins with '-----BEGIN RSA PRIVATE KEY-----...'
const privateKey = fs.readFileSync('./private.key')
const pubKeyObject = crypto.createPublicKey({
key: privateKey,
format: 'pem'
})
const publicKey = pubKeyObject.export({
format: 'pem',
type: 'spki'
})
// -----BEGIN PUBLIC KEY-----...
console.log(publicKey)
Upvotes: 28
Reputation: 302
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))
Upvotes: 11