Java Keystores

Published: Sunday, 14 January 2007

Converting between keystore formats

Sample code attached is where an IBM/AIX server had a pcks12 format keystore, and we needed the same key but for Windows/jks. The problem is that Windows Java could not read the pcks12 format, but the IBM/AIX Java could read both, so the conversion code was run on that machine.

KeyStore kspkcs12=KeyStore.getInstance("PKCS12");
String inputPassword = "staging";
kspkcs12.load(new FileInputStream("staging.p12"), inputPassword.toCharArray());
KeyStore ksjks=KeyStore.getInstance("JKS");
ksjks.load(null, inputPassword.toCharArray());
Certificate c[]=kspkcs12.getCertificateChain("staging");
Key key=kspkcs12.getKey("staging",inputPassword.toCharArray());

String outputPassword = "staging";
ksjks.setKeyEntry("staging", key, outputPassword.toCharArray(),c);
OutputStream outJKS = new FileOutputStream("staging.jks");
ksjks.store(outJKS, outputPassword.toCharArray());
outJKS.close();