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.
The PEM file supplied to the Hybrid Data Pipeline server must include the SSL certificate private and public keys, any intermediate certificates, and the root certificate. A PEM encoded file includes Base64 data.
You can't require a PEM file - that's only used for JS & JSON files. The error is a complaint that the PEM file is not valid JS syntax. To read raw data from other files, including PEM, you can use the fs module: https://nodejs.org/api/fs.html. Save this answer.
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)
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With