我正在尝试使用标准格式的nodejs从PEM格式中提取证书的主题名称,应该看起来像 " C =我们,ST =加利福尼亚,L =旧金山,O = Wikimedia Foundation,Inc。,CN =*。Wikipedia.org"
我能够使用x509-package(https://www.npmjs.com/package/x509(提取主题名称,然后是命令
var subject = x509.getSubject(pem_cert);
但是,此格式为
{ commonName: '*.wikipedia.org',
serialNumber: 'some_number',
countryName: 'US'
}
我需要格式等于标准格式,是否有一个nodejs软件包或命令具有该特定输出?
您可以使用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, ..."
如果您的OPENSL命令行实用程序可在Node.js正在运行的OS上可用,则可以调用它以获取主题字符串:
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();
由于Nodejs 15.6,您最好使用标准crypto
模块: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=ESnO=The Cert CorpnCN=example.com'