Is it possible to use Java Keystore to store password, particularly for WebServices and such? I found online information about storing SSL keys, but this is an over-kill for my needs.
Yes, depending on the type of key store, you can create a SecretKeyEntry
in a KeyStore
. The SunJCE provider implements a "JCEKS" key store that accommodate secret key entries.
static byte[] getPassword(KeyStore ks, String alias, char[] master)
throws GeneralSecurityException, DestroyFailedException
{
if (!ks.entryInstanceOf(alias, KeyStore.SecretKeyEntry.class))
throw new IllegalArgumentException();
KeyStore.PasswordProtection pp = new KeyStore.PasswordProtection(master);
try {
KeyStore.SecretKeyEntry e = (KeyStore.SecretKeyEntry) ks.getEntry(alias, pp);
return e.getSecretKey().getEncoded();
}
finally {
pp.destroy();
}
}
static void setPassword(KeyStore ks, String alias, byte[] password, char[] master)
throws GeneralSecurityException, DestroyFailedException
{
SecretKey wrapper = new SecretKeySpec(password, "RAW");
KeyStore.SecretKeyEntry entry = new KeyStore.SecretKeyEntry(wrapper);
KeyStore.PasswordProtection pp = new KeyStore.PasswordProtection(master);
try {
ks.setEntry(alias, entry, pp);
}
finally {
pp.destroy();
}
}
You should be careful to "zero" the passwords as soon as you are done using them, just like I destroy()
the PasswordProtection
instance in a try-finally block. Otherwise a memory scraper like that used in the Target breach has a better chance of grabbing a key.