Given a simple Node.js app:
var https = require('https');
var fs = require('fs');
var options = {
key: fs.readFileSync('mykey.pem'),
cert: fs.readFileSync('mycert.pem')
};
https.createServer(options, function (req, res) {
console.log(req.connection.getPeerCertificate());
res.writeHead(200);
res.end("hello world\n");
}).listen(8000);
Results in output to the console with a representation of the certificate, not the original (PEM) format.
Are there other methods available to access the original?
The certificate object returned by getPeerCertificate
has a raw
field holding the DER encoding of the certificate.
You can work with this DER encoding directly:
const cert_der = req.connection.getPeerCertificate().raw;
console.log(cert_der);
In general, having the DER encoding should be sufficient. However, if you need the PEM encoding, you can construct it by applying the base64 encoding to the DER encoding:
const os = require('os');
function der_to_pem(der) {
const header = '-----BEGIN CERTIFICATE-----';
const footer = '-----END CERTIFICATE-----';
return [header, der.toString('base64'), footer].join(os.EOL);
}
You could then use this helper function to obtain the PEM encoding of the client certificate:
const cert_der = req.connection.getPeerCertificate().raw;
console.log(der_to_pem(cert_der));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.