Search code examples
node.jsssl

Get public key from certificate in nodejs


I need to get a server's public key from its SSL cert. I'm getting the cert as follows:

https.request(options, res => {
  const cert = res.connection.getPeerCertificate();
  const publicKey = cert.????()
}

I can't find a way to get the public key from the certificate though. Are there any libraries that can do this?

I'm looking to use the public key to encrypt some data:

const encryptedBuffer =  crypto.publicEncrypt({
  key: publicKey,
  padding: crypto.constants.RSA_PKCS1_PADDING
}, utf8Payload)

I see that the certificate has a "raw" buffer, but using that as the publicKey fails.


Solution

  • I see that the certificate has a "raw" buffer, but using that as the publicKey fails.

    Note that the raw buffer is DER encoded, and from crypto.publicEncrypt needs a PEM encoded key. So, you just need to do the conversion. I've used node-openssl-wrapper in the example below, but there are other libraries that also convert DER to PEM,

    const ossl = require('openssl-wrapper')
    const https = require("https");
    
    https.request(options, res => {
        const certificate = res.connection.getPeerCertificate();
        const rawDer = certificate.raw;
    
        ossl.exec('x509', rawDer, { inform: 'der', outform: 'pem' }, (err, buffer) => {
            const publicKey = buffer.toString('utf8'); // PEM encoded public key safe to use now
            // crypto.publicEncrypt({ key: publicKey, ...
        })
    });