Elon Salfati
Elon Salfati

Reputation: 1687

Get cert body and private key from p12 node-forge

I'm trying to get the certificate body and key (PEM format) from a p12 instance from node-forge.

I saw this answer to a similar question but from some reason it doesn't work for me.

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);

bag.asn1 isn't something that exists on the bag instance.

Any ideas?

Upvotes: 5

Views: 6638

Answers (1)

stasinua
stasinua

Reputation: 79

It would be much simpler task if you know what kind of private key used in your .p12 file:

1) In case of RSA key you can get private key from "p12" object by example from official repository of "node-forge":

// get key bags
var bags = p12.getBags({bagType: forge.pki.oids.keyBag});
// get key
var bag = bags[forge.pki.oids.keyBag][0];
var key = bag.key;

2) In my case it was PKCS8 key. To get it you can use example from "node-forge" issues:

var keyBags = p12.getBags({bagType: forge.pki.oids.pkcs8ShroudedKeyBag});
var bag = keyBags[forge.pki.oids.pkcs8ShroudedKeyBag][0];
var privateKey = bag.key;

3) In case of ECC key "node-forge" is not an option according to following open issue: "PKCS12 to PEM"

Unfortunately, we haven't yet implemented ASN.1 parsing for ECC keys, only RSA keys. Forge has an implementation for ed25519 but using only the raw (much simpler) format. PRs are welcome!

Upvotes: 4

Related Questions