How parse a Certificate Signing Request (CSR) file with Javascript to get the subject?

82 Views Asked by At

I read a Certificate Signing Request in X.509 format. I have tried to parse it with the class X509Certificate from NodeJS 'crypto' library. The input format is a string

-----BEGIN CERTIFICATE REQUEST-----
MII....
-----END CERTIFICATE REQUEST-----

I want to get the subject from this certificate signing request (CN, emailAddress, C,...)

I tried the following code

const { X509Certificate } = await import('crypto');
const x509CSR = new X509Certificate(pem)

But the the following error is displayed:

error:0909006C:PEM routines:get_name:no start line

So I have tried another library called 'node-forge'.

const { pki } = await require('node-forge');
x509CSR = pki.certificationRequestFromPem(pem);

But the the following error is displayed:

Cannot read public key. OID is not RSA.

How to get the subject data from the certificate signing request in a NodeJS server?

2

There are 2 best solutions below

0
Shamaz saeed On

You can use jsrsasign library

npm install jsrsasign
const jsrsasign = require('jsrsasign');

const csr = new jsrsasign.asn1.csr.CSRUtil();
const csrObj = csr.pemToCSR(pem);

const subject = csrObj.subject;

console.log(subject);

0
Xavier Ottolini On

I tried your solution.

Thans you for your solution! The jsrsasign is the good library. But the version 11.1.0 implementation has a little bit changed. The following solution fixed the problem:

const jsrsasign = await require('jsrsasign');
const csrUtil = jsrsasign.asn1.csr.CSRUtil;
const csrObj: ParamResponse = csrUtil.getParam(pem);
const subject = csrObj.subject;
console.log(subject)

Not that subject property has two properties: str and array. str is a stringified version of the subject and array is a properties list.