After creating secret keys, how do I store them using the Keystore class' methods and how do I load the keys?
A Java KeyStore (JKS) is a repository of security certificates – either authorization certificates or public key certificates – plus corresponding private keys, used for instance in TLS encryption. In IBM WebSphere Application Server and Oracle WebLogic Server, a file with extension jks serves as a keystore.
Java KeyStores are used to store key material and associated certificates in an encrypted and integrity protected fashion. Like all things Java, this mechanism is pluggable and so there exist a variety of different options.
'cacerts' is a truststore. A trust store is used to authenticate peers. A keystore is used to authenticate yourself.
Keystore is used to store private key and identity certificates that a specific program should present to both parties (server or client) for verification. Truststore is used to store certificates from Certified Authorities (CA) that verify the certificate presented by the server in SSL connection.
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With