I'm trying to extract the Subject Name of a certificate from the PEM format using NodeJS, in the standard format, which should look like "C=US, ST=California, L=San Francisco, O=Wikimedia Foundation, Inc., CN=*.wikipedia.org"
I am able to extract the subject name using the x509-package (https://www.npmjs.com/package/x509), and then the command
var subject = x509.getSubject(pem_cert);
however, this formats it as such
{ commonName: '*.wikipedia.org',
serialNumber: 'some_number',
countryName: 'US'
}
I need the format to be equal to the standard format, is there a NodeJS package or command that will have that specific output?
You can get the certificate subject in the required format by using node-forge
const pki = require('node-forge').pki;
const certPem = `
-----BEGIN CERTIFICATE-----
your certificate here
-----END CERTIFICATE-----
`;
const cert = pki.certificateFromPem(certPem);
const subject = cert.subject.attributes
.map(attr => [attr.shortName, attr.value].join('='))
.join(', ');
console.log(subject); // "C=US, ST=California, ..."
If you have openssl command line utility available on the OS where Node.js is running you can invoke it to get the subject string as well:
const { spawn } = require('child_process');
const certPem = `
-----BEGIN CERTIFICATE-----
your certificate here
-----END CERTIFICATE-----
`;
const child = spawn('openssl', ['x509', '-subject', '-noout']);
child.stdin.write(certPem);
let data = '';
child.stdout.setEncoding('utf-8');
child.stdout.on('data', (chunk) => {
data += chunk
});
child.on('close', () => {
const subject = data.replace(/^subject=/, '');
console.log(subject);
});
child.stdin.end();
Since nodejs 15.6, you would better use the standard crypto
module:
https://nodejs.org/api/crypto.html#x509subject
const crypto = require("crypto")
const cert = new crypto.X509Certificate(fs.readFileSync('my.crt')))
console.log(cert.subject)
// Gives 'C=ES\nO=The Cert Corp\nCN=example.com'
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