Thursday, October 25, 2012

How to create self signed certificates programmatically ?

The most common approach of generating a self-signed certificate is using the  java keytool.

There may be a situation when you want to create a self signed certificates programmatically One approach of programmatically generating these self-signed certificates is through the Bouncy Castle API.

To start with this, you need to have the Bouncy Castle jar in your classpath.(You can download it from here)

Steps to generate self signed certificate key:

1. Create a public/private key pair for the new certificate

        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(1024, new SecureRandom());
        KeyPair keyPair = keyPairGenerator.generateKeyPair();


2. Create new certificate Structure

        X509V3CertificateGenerator v3CertGen =  new X509V3CertificateGenerator();
        v3CertGen.setIssuerDN(new X509Principal("CN=cn, O=o, L=L, ST=il, C= c"));
        v3CertGen.setNotBefore(new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24));
        v3CertGen.setNotAfter(new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 365*10)));
        v3CertGen.setSubjectDN(new X509Principal("CN=cn, O=o, L=L, ST=il, C= c"));
        cert = v3CertGen.generateX509Certificate(keyPair.getPrivate());

3. Store the Certificate with the private key

       KeyStore keyStore = KeyStore.getInstance("JKS");   
        keyStore.load(null, null);
        keyStore.setKeyEntry("YOUR_CERTIFICATE_NAME", key, "YOUR_PASSWORD".toCharArray(),  new[]{cert});
        File file = new File(".", "keystore.test"); new FileOutputStream(file), "YOUR_PASSWORD".toCharArray() );

I have uploaded the tutorial over here.