How to store and load keys using java.security.Key

2019-02-01 19:29发布

问题:

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

回答1:

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



回答2:

I had a situation where I didn't know the key alias name, but I knew there was only one key was there in the keystore. I used the following code to load the key (after loading the keystore as shown above):

Enumeration<String> aliases = keyStore.aliases();
String alias = aliases.nextElement();
KeyStore.PrivateKeyEntry keyEnt = (KeyStore.PrivateKeyEntry) keyStore.getEntry(alias,
                    new KeyStore.PasswordProtection(keystorePass.toCharArray()));
PrivateKey privateKey = keyEnt.getPrivateKey();

I have added a post on my blog with details of how to load the private key, public key and how to use them.



标签: java security