Monday, February 8, 2010

Exporting keys from keystore

Recently I had a similar feeling to one I had writing one of previous posts. It appeared that standard java tools do not have some basic functionality, which obviously (well, probably just for me :) ) should be there. Now I had to export key stored in keystore to share it with other department. It appeared, that keytool can't do that and you have to write tiny program by yourself. Not a big problem, really, it's even nice.

There are lots of posts in web describing how to solve that problem, and here is the best code example I found so far to solve that it.
And here is copy/paste of code snipped, just in case if original post will pass away.


File keystoreFile = new File("The filename of the keystore");
KeyStore ks = KeyStore.getInstance("JKS"); // or whatever type of keystore you have
char[] pw = "the keystore password".toCharArray();
InputStream in = new FileInputStream(keystoreFile);
ks.load(in, pw);
in.close();
for (Enumeration en = ks.aliases(); en.hasMoreElements();)
{
String alias = en.nextElement();
System.out.println(" Alias\t:" + alias);
// If the key entry password is not the same a the keystore password then change this
KeyStore.Entry entry = ks.getEntry(alias, new KeyStore.PasswordProtection(pw));
if (entry instanceof KeyStore.SecretKeyEntry) {
System.out.println(" SecretKey");
KeyStore.SecretKeyEntry skEntry = (KeyStore.SecretKeyEntry) entry;
SecretKey key = skEntry.getSecretKey();
System.out.println(" alg\t: " + key.getAlgorithm());
} else if (entry instanceof KeyStore.PrivateKeyEntry) {
System.out.println(" PrivateKey");
KeyStore.PrivateKeyEntry pkEntry = (KeyStore.PrivateKeyEntry) entry;
PrivateKey key = pkEntry.getPrivateKey();
System.out.println(" alg\t: " + key.getAlgorithm());
java.security.cert.Certificate certificate = pkEntry.getCertificate();
System.out.println(" Certificate type\t: " + certificate.getType());
System.out.println(" Public key\t: " + certificate.getPublicKey().getAlgorithm());
} else if (entry instanceof KeyStore.TrustedCertificateEntry) {
System.out.println(" Certificate");
KeyStore.TrustedCertificateEntry certEntry = (KeyStore.TrustedCertificateEntry) entry;
java.security.cert.Certificate certificate = certEntry.getTrustedCertificate();
System.out.println(" type\t: " + certificate.getType());
}
}


If you need to send key to someone, it handy to make it base64 encoded:

byte[] keyData = key.getEncoded();
BASE64Encoder b64Encoder = new BASE64Encoder();
String b64 = b64Encoder.encode(keyData);
System.out.println("-----BEGIN KEY-----");
System.out.println(b64);
System.out.println("-----END KEY-----");