如何从 nodejs 中的解析 x509 证书中获取 public 密钥长度

How to get the public key length out of parsed x509 certification in nodejs

x509 认证新手。使用 node-js 和大多数(看起来像)工具来创建和解析证书 - node-forge。 我想弄清楚如何获得可靠的 public 密钥长度和签名哈希算法 (SHA) 从基于证书数据创建的证书中。我从 .cert 文件中获取二进制代码并尝试对其进行解析并获取上述数据。看我的基本代码:(cert是代表认证的对象)

let certificateContent = file.replace('-----BEGIN CERTIFICATE-----', '').replace('-----END CERTIFICATE-----', '').trim();
certificateContent = Buffer.from(certificateContent.toString(), 'binary').toString('base64').toString().split(/(.{64})/).filter(x => x).join('\r\n');
let derData = forge.util.decode64(certificateContent);
let cert = forge.pki.certificateFromAsn1(forge.asn1.fromDer(derData));

您可以使用 forge 公开的便捷 certificateFromPem 函数从证书 .pem 文件中获取模数长度 (n),从而获取 public 密钥长度。

我们还可以获得签名Object Id,我们可以在这里查找:http://www.oid-info.com/.

const forge = require('node-forge');
const fs = require('fs');

function getCertificatePublicKeyBitLength(pemFile) {
    const certificate = forge.pki.certificateFromPem(fs.readFileSync(pemFile));
    return certificate.publicKey.n.bitLength();
}
function getCertificateSignatureObjectId(pemFile) {
    const certificate = forge.pki.certificateFromPem(fs.readFileSync(pemFile));
    return certificate.signatureOid;
}

console.log("Bit length: ", getCertificatePublicKeyBitLength('cert.pem'));
console.log("Certificate Signature Object Id: ", getCertificateSignatureObjectId('cert.pem'));

我已经通过使用 openssl 创建证书来对此进行了测试(此处为 4096 位密钥):

openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365