Skip to content Skip to sidebar Skip to footer

Node Js, How To Extract X.509 Certificate From P12 File?

I have p12 file, where I should get X.509 Certificate. In order to work with this file I use forge library: var forge = require('node-forge'); var fs = require('fs'); var keyFile

Solution 1:

According to [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.

So, you need 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-encodevar msg = {
  type: 'CERTIFICATE',
  body: forge.asn1.toDer(bag.asn1).getBytes()
};
var pem = forge.pem.encode(msg);

console.log(pem);

Post a Comment for "Node Js, How To Extract X.509 Certificate From P12 File?"