header

Torsten Curdt’s weblog

Client cert authentication with java

Connecting to https URL is easy in java. Just create a URL object and you are ready to go. If you need to provide a client certificate it gets a little more complicated to get it right. Basically you have to create a properly set up SSLSocketFactory to establish an authenticated connection. You have to load you PKCS12 certificate into a keystore and provide that store to the SSLContext.

private SSLSocketFactory getFactory( File pKeyFile, String pKeyPassword ) throws ... {
  KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509);
  KeyStore keyStore = KeyStore.getInstance("PKCS12");

  InputStream keyInput = new FileInputStream(pKeyFile);
  keyStore.load(keyInput, pKeyPassword.toCharArray());
  keyInput.close();

  keyManagerFactory.init(keyStore, pKeyPassword.toCharArray());

  SSLContext context = SSLContext.getInstance("TLS");
  context.init(keyManagerFactory.getKeyManagers(), null, new SecureRandom());

  return context.getSocketFactory();
}

URL url = new URL("https://someurl");
HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
con.setSSLSocketFactory(getFactory(new File("file.p12"), "secret"));

If the client certificate was issued by your private CA you also need to make sure the full certificate chain is in your JVMs keystore.

STORE=/path/to/JRE/cacerts
sudo keytool -import -trustcacerts \
  -keystore $STORE \
  -storepass changeit \
  -noprompt \
  -file myca.pem \
  -alias myca

2 Responses to “Client cert authentication with java”

  1. Jon MacLaren said, on 2. December 2006 at 9:23

    Thanks for posting this article. I was looking around for a way to set up the client keystore for an HTTPS client without using the system properties method that is recommended *everywhere* else. (My reason is that the HTTPS client is living inside a servlet, making the system properties method a really bad idea.) It took a good hour or so to track down your page, but eventually, Google provided…

  2. Marco said, on 28. November 2007 at 19:03

    Thank you for taking the time to put this together.

Leave a Reply

Please copy the string An1YTt to the field below: