Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 425
flitbit Avatar asked Feb 27 '15 14:02

flitbit


People also ask

Does PEM contain public key?

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.

How do I read a PEM file in node?

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.


2 Answers

Modern answer NodeJS v11.6.0 (released Dec 2018)

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)  
like image 57
Kevin Avatar answered Oct 01 '22 12:10

Kevin


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))
like image 37
anx Avatar answered Oct 01 '22 10:10

anx