How to decode a .csr file in java to extract its content

9.4k views Asked by At

I have three kinds of files to decode namely .csr and .der and .key files.I am able to decode .der file using the java as below. public class Base64Decoder {

public static void main(String[] args) throws FileNotFoundException, IOException {
    Certificate cert=null;
try{

 FileInputStream fis = new FileInputStream("C:/Users/patillat/Downloads/device-ee/csr/00db1234567890A5-ka.der");
 BufferedInputStream bis = new BufferedInputStream(fis);

 CertificateFactory cf = CertificateFactory.getInstance("X.509");

 while (bis.available() > 0) {
    cert = cf.generateCertificate(bis);
    try {
        System.out.println("-----BEGIN CERTIFICATE-----");
        System.out.println(DatatypeConverter.printBase64Binary(cert.getEncoded()));
        System.out.println("-----END CERTIFICATE-----");
        //System.out.println("key:"+cert.getPublicKey());
    } catch (CertificateEncodingException e) {
        e.printStackTrace();
    }
    System.out.println(cert.toString());
 }
}
catch(Exception e)
{
    e.printStackTrace();
}

}

}

I am able to generate details of .der certificate

In the same way I am not able to decode my .csr file. Are there any other ways to decode .csr files?

3

There are 3 answers

2
primetomas On

Using BouncyCastle you can easily decode a csr, from binary format.

JcaPKCS10CertificationRequest p10Object = new JcaPKCS10CertificationRequest(byte[] csrBytes);

There are also htlper classes for decoding/decoding to/from PEM format (base64 encoded).

0
Mad On

Here's the code that I have used to decode .csr file.

public class CSRInfoDecoder {

private static Logger LOG = Logger.getLogger(CSRInfoDecoder.class.getName());

private static final String COUNTRY = "2.5.4.6";
private static final String STATE = "2.5.4.8";
private static final String LOCALE = "2.5.4.7";
private static final String ORGANIZATION = "2.5.4.10";
private static final String ORGANIZATION_UNIT = "2.5.4.11";
private static final String COMMON_NAME = "2.5.4.3";
private static final String EMAIL = "2.5.4.9";

private static final String csrPEM = "-----BEGIN CERTIFICATE REQUEST-----\n"
        + "MIICxDCCAawCAQAwfzELMAkGA1UEBhMCVVMxETAPBgNVBAgMCElsbGlub2lzMRAw\n"
        + "DgYDVQQHDAdDaGljYWdvMQ4wDAYDVQQKDAVDb2RhbDELMAkGA1UECwwCTkExDjAM\n"
        + "BgNVBAMMBUNvZGFsMR4wHAYJKoZIhvcNAQkBFg9rYmF4aUBjb2RhbC5jb20wggEi\n"
        + "MA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDSrEF27VvbGi5x7LnPk4hRigAW\n"
        + "1feGeKOmRpHd4j/kUcJZLh59NHJHg5FMF7u9YdZgnMdULawFVezJMLSJYJcCAdRR\n"
        + "hSN+skrQlB6f5wgdkbl6ZfNaMZn5NO1Ve76JppP4gl0rXHs2UkRJeb8lguOpJv9c\n"
        + "tw+Sn6B13j8jF/m/OhIYI8fWhpBYvDXukgADTloCjOIsAvRonkIpWS4d014deKEe\n"
        + "5rhYX67m3H7GtZ/KVtBKhg44ntvuT2fR/wB1FlDws+0gp4edlkDlDml1HXsf4FeC\n"
        + "ogijo6+C9ewC2anpqp9o0CSXM6BT2I0h41PcQPZ4EtAc4ctKSlzTwaH0H9MbAgMB\n"
        + "AAGgADANBgkqhkiG9w0BAQsFAAOCAQEAqfQbrxc6AtjymI3TjN2upSFJS57FqPSe\n"
        + "h1YqvtC8pThm7MeufQmK9Zd+Lk2qnW1RyBxpvWe647bv5HiQaOkGZH+oYNxs1XvM\n"
        + "y5huq+uFPT5StbxsAC9YPtvD28bTH7iXR1b/02AK2rEYT8a9/tCBCcTfaxMh5+fr\n"
        + "maJtj+YPHisjxKW55cqGbotI19cuwRogJBf+ZVE/4hJ5w/xzvfdKjNxTcNr1EyBE\n"
        + "8ueJil2Utd1EnVrWbmHQqnlAznLzC5CKCr1WfmnrDw0GjGg1U6YpjKBTc4MDBQ0T\n"
        + "56ZL2yaton18kgeoWQVgcbK4MXp1kySvdWq0Bc3pmeWSM9lr/ZNwNQ==\n"
        + "-----END CERTIFICATE REQUEST-----\n";

public static void main(String[] args) {
    InputStream stream = new ByteArrayInputStream(csrPEM.getBytes(StandardCharsets.UTF_8));

    CSRInfoDecoder m = new CSRInfoDecoder();
    m.readCertificateSigningRequest(stream);
}

public String readCertificateSigningRequest(InputStream csrStream) {

    PKCS10CertificationRequest csr = convertPemToPKCS10CertificationRequest(csrStream);
    String compname = null;

    if (csr == null) {
        LOG.warn("FAIL! conversion of Pem To PKCS10 Certification Request");
    } else {
       X500Name x500Name = csr.getSubject();

       System.out.println("x500Name is: " + x500Name + "\n");

       RDN cn = x500Name.getRDNs(BCStyle.EmailAddress)[0];
       System.out.println(cn.getFirst().getValue().toString());
       System.out.println(x500Name.getRDNs(BCStyle.EmailAddress)[0]);
       System.out.println("COUNTRY: " + getX500Field(COUNTRY, x500Name));
       System.out.println("STATE: " + getX500Field(STATE, x500Name));
       System.out.println("LOCALE: " + getX500Field(LOCALE, x500Name));
       System.out.println("ORGANIZATION: " + getX500Field(ORGANIZATION, x500Name));
       System.out.println("ORGANIZATION_UNIT: " + getX500Field(ORGANIZATION_UNIT, x500Name));
       System.out.println("COMMON_NAME: " + getX500Field(COMMON_NAME, x500Name));
       System.out.println("EMAIL: " + getX500Field(EMAIL, x500Name));
    }
    return compname;
}


private String getX500Field(String asn1ObjectIdentifier, X500Name x500Name) {
    RDN[] rdnArray = x500Name.getRDNs(new ASN1ObjectIdentifier(asn1ObjectIdentifier));

    String retVal = null;
    for (RDN item : rdnArray) {
        retVal = item.getFirst().getValue().toString();
    }
    return retVal;
}

private PKCS10CertificationRequest convertPemToPKCS10CertificationRequest(InputStream pem) {
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    PKCS10CertificationRequest csr = null;
    ByteArrayInputStream pemStream = null;

    pemStream = (ByteArrayInputStream) pem;

    Reader pemReader = new BufferedReader(new InputStreamReader(pemStream));
    PEMParser pemParser = null;
    try {
        pemParser = new PEMParser(pemReader);
        Object parsedObj = pemParser.readObject();
        System.out.println("PemParser returned: " + parsedObj);
        if (parsedObj instanceof PKCS10CertificationRequest) {
            csr = (PKCS10CertificationRequest) parsedObj;
        }
    } catch (IOException ex) {
        LOG.error("IOException, convertPemToPublicKey", ex);
    } finally {
        if (pemParser != null) {
            IOUtils.closeQuietly(pemParser);
        }
    }
    return csr;
}

}

In the above code, I have converted the csrPem String into a InputStream for my own testing purposes so you can eliminate that step and directly useByteArrayInputStream`.

0
dapc On

One can utilize Bouncycastle in order to achieve this. See code snippet below for parsing a String to a PKCS10CertificationRequest. Of course you can replace the ByteArrayInputStream to a arbitrary input stream of your choice.

try (final ByteArrayInputStream bais = new ByteArrayInputStream(csrAsString.getBytes());
     final InputStreamReader isr = new InputStreamReader(bais, StandardCharsets.UTF_8);
     final PEMParser pem = new PEMParser(isr))
{
     PKCS10CertificationRequest csr = (PKCS10CertificationRequest) pem.readObject();
     // Do your verification here
}