Geraint Anderson
Geraint Anderson

Reputation: 3393

Convert certificate in p12 file to base64

I have a p12 certificate which I need to use to create digital signatures to be sent in the headers of a HTTP request. I'm using the node-forge package to get the privateKey and certificate bags from the p12.

const p12Asn1 = forge.asn1.fromDer(keyFile)
const p12 = forge.pkcs12.pkcs12FromAsn1(p12Asn1, passwordHash)
const certificateBags = p12.getBags({ bagType: forge.pki.oids.certBag })
const certificate = certificateBags[forge.pki.oids.certBag][0].cert

I have instructions from the API vendor on creating the digital signature. One step is:

keyId - Get X509 certificate that accompanies the private key as a byte array and Base64 encode. This field is required.

How can I Base64 encode the certificate extracted from the bags above? I have tried various forge utility methods, forge.util, but the certificate is an object at this point so I'm not sure what bit needs encoding.

Upvotes: 0

Views: 1391

Answers (1)

IvanCupRs
IvanCupRs

Reputation: 1

Maybe is a bit late, but...

Once you have the certificate, you need convert to PEM and then convert to b64, as like documentation:

// convert a Forge certificate to PEM<br/>
var pem = forge.pki.certificateToPem(certificate);

// encode base64 <br/>
var encoded = forge.util.encode64(pem);

And you have the certificate as byte array b64, the API vendor will need to decode de b64 array and then covert as "X509Certificate".

Upvotes: 0

Related Questions