Node JS,如何从 P12 文件中提取 X.509 证书?

Node JS, how to extract X.509 Certificate from P12 file?

我有 p12 文件,我应该从中获取 X.509 证书。为了使用这个文件,我使用 forge library:

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

var keyFile = fs.readFileSync("/path/to/p12/file.p12", 'binary');
var p12Asn1 = forge.asn1.fromDer(keyFile);

var p12 = forge.pkcs12.pkcs12FromAsn1(p12Asn1, 'password');

var bags = p12.getBags({bagType: forge.pki.oids.certBag});

var cert = bags[forge.pki.oids.certBag][0];

console.log(cert);

控制台向我输出这样的信息:

{ type: '1.2.840.113549.1.12.10.1.3',
  attributes:
  { localKeyId: [ 'aoa ??xx\u0015-?]%m§ §\f,\u0013' ],
    friendlyName: [ 'e56fe5a0899f787815adaf5d256da7a0a70c2c13' ] },
    cert: null,
    asn1:
    { tagClass: 0,
      type: 16,
      constructed: true,
      composed: true,
      value: [ [Object], [Object], [Object] ] } }

这个结果意味着我有一个名为 e56fe5a0899f787815adaf5d256da7a0a70c2c13 的别名,但为什么 certnull

有 Java 的安全性 api,它能够通过别名从此 p12 文件中提取 X.509 证书。

X509Certificate x509Certificate = (X509Certificate) ks.getCertificate(alias);

如何使用 forgep12 文件中提取 X.509 证书?

节点版本5.4.1

锻造版0.6.45

在那里你可以下载我的测试p12文件:link

密码是123456

根据[https://github.com/digitalbazaar/forge/issues/237#issuecomment-93555599]:

If forge doesn't recognize the key format, it will return null for the key property in the key bag, and set an asn1 property with the raw ASN.1 representation of the key.

所以,你需要convert to ASN.1, then DER, then PEM-encode:

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

var keyFile = fs.readFileSync("./gost.p12", 'binary');
var p12Asn1 = forge.asn1.fromDer(keyFile);

var p12 = forge.pkcs12.pkcs12FromAsn1(p12Asn1, '123456');

var bags = p12.getBags({bagType: forge.pki.oids.certBag});

var bag = bags[forge.pki.oids.certBag][0];

// convert to ASN.1, then DER, then PEM-encode
var msg = {
  type: 'CERTIFICATE',
  body: forge.asn1.toDer(bag.asn1).getBytes()
};
var pem = forge.pem.encode(msg);

console.log(pem);