Home > database >  How can I extract alternative names data from a CSR?
How can I extract alternative names data from a CSR?

Time:10-07

I have a CSR and I can parse all the data with pkijs.org lib, but I have no luck to parse alternative names data. How is it possible to do with a javascript? Some other libs can be in use, I guess, do you know one?

CodePudding user response:

Following the docs of CertificationRequest class provided by pkijs here https://pkijs.org/docs/classes/CertificationRequest.html. We can see that the structure of a CSR. The subject alternative name will be stored in attributes propery of CertificationRequest object. But the structure inside of attributes is quite complex to make it as plain text. This is my code used to print out the subject alternative name

const pkijs = require('pkijs');
const utils = require("pvtsutils");
const asn1js = require("asn1js");

let base64 = "<your_csr_in_base64>"
    let csrraw = utils.Convert.FromBase64(base64);
    console.log(csrraw)
    const pkcs10 = pkijs.CertificationRequest.fromBER(csrraw);
    let seq =   pkcs10.attributes[0].values[0];  
    let exts = pkijs.Extensions.fromBER(seq.toBER(false));
    console.log(exts); 
    var san = getExtentionsForSANFromExtensions(exts);
    console.log(san)
    if (san != undefined) {
      san.names.forEach(element => {
          console.log(element.type   " = "   element.value)
      });
    }


function getExtentionsForSANFromExtensions(exts){
  for (var i = 0 ; i< exts.extensions.length; i  ) {
    var ext = exts.extensions[i];
    if(ext.extnID == '2.5.29.17') {
      var octetString = asn1js.fromBER(ext.extnValue.toBER(false)).result; 
      return pkijs.GeneralNames.fromBER(octetString.getValue());
    }         
  }
}

I've tested this code and it works properly with CSR generated by Keystore Explorer. Have not tested with another tool to generate CSR that supports subject alternative names.

Cheers!

CodePudding user response:

If you have a CSR and need to extract the alternative names data from it, you can use the following command:

openssl req -in csr.pem -noout -text

This will print out the entire CSR, including the alternative names data.

  • Related