Create a CSR in Java



http://www.bouncycastle.org/latest_releases.html

javac -cp ".:/usr/share/java/bcprov-jdk16-145.jar" CSRGenerator.java

java -cp ".:/usr/share/java/bcprov-jdk16-145.jar" CSRGenerator

CSRGenerator.java
import org.bouncycastle.jce.PKCS10CertificationRequest;
import java.net.URL;
import java.security.*;
import java.security.cert.*;
import java.io.*;
import javax.security.auth.x500.X500Principal;
import org.bouncycastle.openssl.PEMWriter;
 
 
 
public class CSRGenerator
{
    public static void main(String[] args) throws Exception
    {
        Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
 
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
        keyGen.initialize(2048);
        KeyPair keypair = keyGen.genKeyPair();
        PrivateKey privateKey = keypair.getPrivate();
        PublicKey publicKey = keypair.getPublic();
 
        //X500Principal subject = new X500Principal("CN=Test V3 Certificate");
        X500Principal subject = new X500Principal("CN=local.zedwood.com, O=zedwood, OU=org, L=Orem, ST=Utah, C=US");
 
        PKCS10CertificationRequest csr = new PKCS10CertificationRequest( 
                           "SHA1withRSA",
                           subject,
                           keypair.getPublic(),
                           null,
                           keypair.getPrivate()
                );
 
        //byte[] outBytes = csr.getEncoded();
        //FileOutputStream f = new FileOutputStream("outfile.csr_bin");
        //f.write(outBytes);
        //f.close();
 
        FileWriter fw = new FileWriter("outfile.csr");
        PEMWriter pm = new PEMWriter(fw);
        pm.writeObject(csr);
        pm.close();
        fw.close();
    }
 
}

code snippets are licensed under Creative Commons CC-By-SA 3.0 (unless otherwise specified)