condinya condinya - 2 months ago 12
Java Question

How to store and load keys using java.security.KeyStore class

After creating secret keys, how do I store them using the Keystore class' methods and how do I load the keys?

Answer

Storing:

KeyStore ks = KeyStore.getInstance("JKS");
ks.setKeyEntry("keyAlias", key, passwordForKeyCharArray, certChain);
OutputStream writeStream = new FileOutputStream(filePathToStore);
ks.store(writeStream, keystorePasswordCharArray);
writeStream.close();

Note thet certChain might be null, unless you are passing PrivateKey

Loading:

KeyStore ks = KeyStore.getInstance("JKS");
InputStream readStream = new FileInputStream(filePathToStore);
ks.load(readStream, keystorePasswordCharArray);
Key key = ks.getKey("keyAlias", passwordForKeyCharArray);
readStream.close();

Read the javadocs

EDIT:

Note that if you are storing a SecretKey or using any part of the SunJCE provider (Java Cryptography Extension), you will need to set your KeyStore type to JCEKS.

KeyStore ks = KeyStore.getInstance("JCEKS");

I'd appreciate if you explain How can i use this with my ssl/tls application (sslserversocketfactory) i need to give it the path of a CA certificate