Merge Java Keystores Programmatically

Merging Java Keystores dynamically sounds more complex as it really is. You can also use this approach to create one keystore out of an arbitrary number of keystores. Well, you definitely should know their passwords.. However, my use case was quite interesting: Virtualhosts running in jetty should use SSL+SNI. Using SNI requires you to provide one keystore with all credentials from all virtualhosts. But unfortunately, the virtualhosts each had its own keystore. So in order to get it running, the keystores needed to be merged.

/**
* @param newKeystore
* @param oldKeystore
* @throws Exception
*/
private void mergeKeystores(KeyStore newKeystore, KeyStore oldKeystore) throws Exception{
// Get all aliases in the old keystore
Enumeration enumeration = oldKeystore.aliases();
while(enumeration.hasMoreElements()) {
  // Determine the current alias
  String alias = enumeration.nextElement();
  // Get Key & Certificates
  Key key = oldKeystore.getKey(alias, sPassword);
  Certificate[] certs = oldKeystore.getCertificateChain(alias);
  // Put them altogether in the new keystore
  newKeystore.setKeyEntry(alias, key, sPassword, certs);
}
}

Create a new Java Keystore

If you want to create a new keystore, you need to pass 'null' for the InputStream.

KeyStore newKeystore = KeyStore.getInstance(KeyStore.getDefaultType());
newKeystore.load(null, "SUPER_SECRET_PASSWORD".toCharArray());

Save Java Keystore

I see a lot of dirty code on Stackoverflow. Please always stick to clean code and (I really like this feature) use Auto-Closeables!

File fNewKeystore = new File("/home/max/keystore.jks");
try(FileOutputStream out = new FileOutputStream(fNewKeystore);) {
  newKeystore.store(out, "SUPER_SECRET_PASSWORD".toCharArray());
}

Leave a Comment

comments powered by Disqus