Generating Self-signed Certificates for Mutual Authentication in Java
This post is a follow up to my previous post on Generating Self-Signed Certificate for use in Java. This post will follow many of the same steps, but will show you how to generate both server and client certificates for use with mutual authentication (Two-Way SSL). Once again we will be using OpenSSL and Java Keytool.
1) Create private keys using OpenSSL
The private keys are 2048 bits long and generated using the RSA algorithm. They are not protected with an additional pass phrase.2) Create self-signed X509 certificates
For each command you will be prompted to enter a few pieces of information, use “.” if you wish to leave the field blank.NOTE: The field Common Name is quite important here. It is the hostname of the machine you are trying to certify with the certificate, which is the name in the DNS entry corresponding to your machine IP.
If you want to avoid having to manually enter all of this information each time, you can use the subj argument and pass all of the relevant information in to OpenSSL. If you use the subj argument, the command will look like this:
Obviously you will need to replace my information with yours.
3) Create JKS trust stores
In order to use our keys and certificates in Java applications we need to import them into keystores.
4) Create PKCS12 keystores and import the certificates
Java's keytool application will not let us import an existing private key into a keystore. The workaround to this problem is to combine the private key with the certificate into a pkcs12 file and then import this pkcs12 keystore into a regular keystore.
5) Convert the PKCS12 keystores to Java keystores using Java keytool
Keytool will first ask you for the new password for the JKS keystore twice, and it will also ask you for the password you set for the PKCS12 keystore created earlier.It will output the number of entries successfully imported, failed, and cancelled.
If nothing went wrong, you should have 2 new keystore files: server.jks & client.jks.
6) Configure server
Depending on how you are using your keys, you will now need to configure your server. The file server.jks contains your servers self signed certificate, and the file server_truststore.jks contains your servers trust store that trusts your client certificate.
For an example of how to configure SSL using an Embedded Jetty server, see Using SSL with Embedded Jetty
7) Configure client
Depending on how you are using your keys, you will now need to configure the client. The file client.jks contains your servers self signed certificate, and the file client_truststore.jks contains your clients trust store that trusts your server certificate.
If your are going to be using a browser as the client, then you will want to import the client.p12 file into your browser.
References
- http://www.openssl.org/docs/HOWTO/
- http://docs.oracle.com/javase/1.3/docs/tooldocs/win32/keytool.html