Monday, December 14, 2009

Keytool keystore Cannot store non-PrivateKeys

Don't believe the error, or a lot of websites....

I have a requirement to encrypt passwords in a file. I figured I'd use the java security tools to store the encryption key.

Step 1/ Generate the secret key (Using AES as encryption algorithm)
.\keytool -genseckey -alias aestest -keyalg AES -keysize 192

This results in error
keytool error: Cannot store non-PrivateKeys

After much searching, and some incorrect pointers (Keytool cannot generate symmetric keys, keytool cannot generate AES keys etc.), I found the solution. The problem is the default Keystore type is JKS. This cannot store symmetric keys. However if you change the keystore type to JCEKS then it works.

.\keytool -genseckey -alias aestest -keyalg AES -keysize 192 -storetype JCEKS

One side effect of this is that you then need to specify the storeType in every command there-after.

keytool -list
keytool error: Invalid keystore format

keytool -list -storetype JCEKS
Your keystore contains 3 entries

aestest, 14-Dec-2009, SecretKeyEntry,
aestest2, 14-Dec-2009, SecretKeyEntry,
test, 14-Dec-2009, SecretKeyEntry,