Java Key Stores

Managing keys and certificates is usually a pain. It's not particularly complicated, but it's done so infrequently that it's hard to remember some of the prickly details. Nice tools are not developed because you only need them once a year or so when certificates expire or a new project comes along. The myriad of file formats don't make the job any easier.

During the development of yet another single sign-on application, a vendor sent us a private key and related certificate in a PFX file. Windows can readily read and import this file format, just double click on it. Java's command line Keytool can read and write X.509 formats, but it can't do anything with PFX files. Of course, OpenSSL will do it all, but I just didn't want to spend several hours installing and learning how to use yet another set of commmand line tools.

It turns out that PFX files are really PKCS#12 files. If you read the fine print in the Java API docs, you will learn that the KeyStore class can read two formats out of the box: JKS and PKCS#12. Reading a PKCS#12 file takes just two lines of code:

    KeyStore pfx = KeyStore.getInstance("pkcs12");
    pfx.load(new FileInputStream("somefile.pfx"), password);

From there, it's just a matter of getting keys and certificates. If you want to write keys and certificates into a JKS keystore compatible with keytool (and the default key store format), just create one:

    KeyStore jks = KeyStore.getInstance("jks");
    pfx.load(null, password);

The second line is necessary to initialize the keystore.

Armed with those golden nuggets, it wouldn't take much to write a nice, intuitive GUI application. Of course, it won't see much use, so it's hard to motivate myself to write it.