Storing Arbitrary Values in Java Keystore

Java Keystore is a nice tool, but it has a very limited number of inputs it supports natively. Mainly those are pem certificates and corresponding keys.

Fortunately, there is a way to store arbitrary data using keytool’s -importpass command and base64 encoding.

Here is how to achieve that. Let’s imagine we have some secret.bin file, we would like to store as a secret. Below is a shell scripting sequence using keytool that would create our keystore (remember to set desired alias and storepass):

base64 -w 0 secret.bin | keytool -importpass -keystore test.jks -alias key1 -storepass mypass

Now, we can read it in Java with code like the following (note, that I’m omitting proper error handling and stream closures – you should use try-with-resources pattern):

char[] pass = "mypass".toCharArray();
KeyStore ks = KeyStore.getInstance("JKS");
ks.load(new FileInputStream("/path/to/test.jks"), pass);
Key mykey = ks.getKey("key1", pass);
byte[] keybytes = mykey.getEncoded();
byte[] decodedKey = Base64.getDecoder().decode(keybytes);

This is it, now decodedKey variable contains your secret binary and you can use it further.