Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

security

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

like image 899
condinya Avatar asked Jun 12 '10 02:06

condinya


People also ask

What is Java security keystore?

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.

Is Java Keystore secure?

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.

Is cacerts a keystore or truststore?

'cacerts' is a truststore. A trust store is used to authenticate peers. A keystore is used to authenticate yourself.

What is the difference between a keystore and a truststore?

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.


1 Answers

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"); 
like image 150
Bozho Avatar answered Sep 29 '22 11:09

Bozho