-1

How can I convert a DER Format certificate x509 into a human readable format in JavaScript?

Pang
  • 9,564
  • 146
  • 81
  • 122

1 Answers1

4

Javascript does not provide a method to parse certificate fields. You need to use a library like forge. I think you need something like this

var certAsn1 = forge.asn1.fromDer(certDer)
var cert = forge.pki.certificateFromAsn1(certAsn1);
console.log(cert.serialNumber);
pedrofb
  • 37,271
  • 5
  • 94
  • 142
  • Probably your data is not in DER format or you have an encoding issue. Please update your question and add the code you are using, the entire error message and the example data you are using. If not, it is not possible to determine the cause – pedrofb Jun 19 '17 at 11:44
  • var pki = forge.pki; var certpem="-----BEGIN CERTIFICATE----------END CERTIFICATE-----"; var cert = pki.certificateFromPem(certpem); console.log("certificat" + cert.validity.notBefore); console.log("certificat" + cert.validity.notAfter); console.log("certificat" + cert.serialNumber);. it works but NOW I don't know how can I get the issuerCN and CN and I have a DER in format Hex – halloulaguesmi Jun 19 '17 at 12:59
  • Do not paste code into comments because it is difficult to read it. Just edit your question and add the information – pedrofb Jun 19 '17 at 15:14
  • To load DER content encoded as HEX, you will need first to decode it. Forge has functions to do it, or look at this site. To load the issuer info try to inspect the javascript object looking for a 'issuer' property or a 'getIssuer()` method. The CN should be a property of that object – pedrofb Jun 19 '17 at 15:18
  • thanks , it work now IssuerCN like this : cert.issuer.getField('CN').value); and CN like this : cert.subject.getField('CN').value); . NOW I have another question please How can I parse DER Hex to PEM ??? thank you very much – halloulaguesmi Jun 20 '17 at 08:26
  • Basically you have to convert HEX-->Binary-->Base64 and add PEM header and footer (`-----BEGIN CERTIFICATE-----`, `-----END CERTIFICATE-----`). It is recommended in Stack Overflow to create a new Post for each question, and add the code used so people could find the errors – pedrofb Jun 20 '17 at 09:08
  • See [doc](https://github.com/digitalbazaar/forge#x509) Pem to Cert: `var cert = forge.pki.certificateFromPem(pem);` Public Key to PEM: `var pem = forge.pki.publicKeyToPem(cert.publicKey);` – pedrofb Jun 21 '17 at 13:30