Home » Java » csr – Generate a Certificate Signing Request for ssl using java program-Exceptionshub

csr – Generate a Certificate Signing Request for ssl using java program-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

I want to write a program that can generate Certificate Signing Request with all information like domain name, country name, state organisation etc. I know to how to generate it with open-ssl but I want to generate it with only java program. How can I do this?

Thanks for your help

How to&Answers:

Bouncy castle provides all the tools you need to do that.

Here is the code to generate a CSR:

    PrivateKey priKey = entry.getPrivateKey(keystore, pwd);
    PKCS10CertificationRequestBuilder p10Builder
            = new JcaPKCS10CertificationRequestBuilder(
                    cert.getSubjectX500Principal(), cert.getPublicKey());
    JcaContentSignerBuilder csBuilder = new JcaContentSignerBuilder(cert.getSigAlgName());
    ContentSigner signer = csBuilder.build(priKey);
    PKCS10CertificationRequest csr = p10Builder.build(signer);
    try (OutputStream stream = new FileOutputStream(file);
            Writer writer = new OutputStreamWriter(stream, "UTF-8");
            JcaPEMWriter out = new JcaPEMWriter(writer)) {
        out.writeObject(csr);
    }