Generating the CSR using BouncyCastle API

Fox picture Fox · Dec 12, 2013 · Viewed 14.8k times · Source

I am new to the security side of Java and stumbled across this library called BouncyCastle. But the examples that they provide and the ones out on the internet ask to use

return new PKCS10CertificationRequest("SHA256withRSA", new X500Principal(
    "CN=Requested Test Certificate"), pair.getPublic(), null, pair.getPrivate()

But when I use PKCS10CertificationRequest, it looks like it is deprecated. So I started looking at another method where I use CertificationRequest class. But I am really confused, the constructor does not take the same parameters instead it takes CertificationRequestInfo class which I am not sure how to fill up.

CertificationRequest request = new CertificationRequest(...);

It would be awesome if someone could help me figure out how to make a CSR so that I can send it to the server for getting it signed.

Answer

Jcs picture Jcs · Dec 12, 2013

With the recent versions of BouncyCastle it is recommended to create the CSR using the org.bouncycastle.pkcs.PKCS10CertificationRequestBuilder class.

You can use this code snipppet:

KeyPair pair = generateKeyPair();
PKCS10CertificationRequestBuilder p10Builder = new JcaPKCS10CertificationRequestBuilder(
    new X500Principal("CN=Requested Test Certificate"), pair.getPublic());
JcaContentSignerBuilder csBuilder = new JcaContentSignerBuilder("SHA256withRSA");
ContentSigner signer = csBuilder.build(pair.getPrivate());
PKCS10CertificationRequest csr = p10Builder.build(signer);