How to generate, sign and import SSL certificate from Java

Demiurg picture Demiurg · Jan 8, 2011 · Viewed 25.8k times · Source

Possible Duplicate:
Generate certificates, public and private keys with Java

I need to generate a self signed certificates at run time, sign them and import to the Java keystore. I can do this using "keytool" and "openssl" from command line in the following way:

keytool -import -alias root -keystore keystore.txt -file cacert.pem
keytool -genkey -keyalg RSA -keysize 1024 -alias www.cia.gov -keystore keystore.txt
keytool -keystore keystore.txt -certreq -alias www.cia.gov -file req.pem
openssl x509 -req -days 3650 -in req.pem -CA cacert.pem -CAkey cakey.pem -CAcreateserial -out reqsigned.pem 
keytool -import -alias www.cia.gov -keystore keystore.txt -trustcacerts  -file reqsigned.pem

I can, of course, ship my application with keytool and openssl binaries and execute the above commands from Java, but I'm looking for a cleaner approach which would allow me to do all of the above using pure Java.

Any libraries I can use ?

Answer

Ray Hulha picture Ray Hulha · Sep 5, 2011
import java.io.FileOutputStream;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.cert.X509Certificate;
import java.util.Date;

// import sun.security.tools.keytool.CertAndKeyGen; // Use this for Java 8 and above
import sun.security.x509.CertAndKeyGen;
import sun.security.x509.X500Name;

public class UseKeyTool {

    private static final int keysize = 1024;
    private static final String commonName = "www.test.de";
    private static final String organizationalUnit = "IT";
    private static final String organization = "test";
    private static final String city = "test";
    private static final String state = "test";
    private static final String country = "DE";
    private static final long validity = 1096; // 3 years
    private static final String alias = "tomcat";
    private static final char[] keyPass = "changeit".toCharArray();

    // copied most ideas from sun.security.tools.KeyTool.java

    @SuppressWarnings("restriction")
    public static void main(String[] args) throws Exception {

        KeyStore keyStore = KeyStore.getInstance("JKS");
        keyStore.load(null, null);

        CertAndKeyGen keypair = new CertAndKeyGen("RSA", "SHA1WithRSA", null);

        X500Name x500Name = new X500Name(commonName, organizationalUnit, organization, city, state, country);

        keypair.generate(keysize);
        PrivateKey privKey = keypair.getPrivateKey();

        X509Certificate[] chain = new X509Certificate[1];

        chain[0] = keypair.getSelfCertificate(x500Name, new Date(), (long) validity * 24 * 60 * 60);

        keyStore.setKeyEntry(alias, privKey, keyPass, chain);

        keyStore.store(new FileOutputStream(".keystore"), keyPass);



    }
}