JAVA KEYSTORE API
INTRODUCTION:
The Java KeyStore is a repository for authorization certificates or public key certificates also contains corresponding private keys. An entry in a KeyStore is identified by an alias and consists of keys and certificates that form a trust chain. We typically save keystores to a file system, and we can protect it with a password.
CONSTRUCTION OF KEYSTORE
We can construct a KeyStore by initializing the instance of the KeyStore by calling its getInstance() method.
KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
We can create KeyStore of other types by simply passing one of the supported formats
KeyStore keyStore = KeyStore.getInstance(“PKCS12”);
LOADING KEYSTORE
To use a KeyStore instance, we first need to load it. KeyStore is usually stored on disk or any other kind of storage.To load a Keystore, we use the KeyStore load() method. The load contains two parameters:
An InputStream which tells from where the KeyStore data has to be loaded.
A char array which stores the password of the KeyStore.
char[] keyStorePassword = “123abc”.toCharArray();
try(InputStream keyStoreData = new FileInputStream(“keystore.ks”)){
keyStore.load(keyStoreData, keyStorePassword);
}
FETCHING KEYS FROM KEYSTORE
Get Vishal R’s stories in your inbox
Join Medium for free to get updates from this writer.
To fetch the keys from the KeyStore instance, we use the getEntry() method. Every key of a KeyStore is mapped with an alias which identifies the key and is protected by a key password. To access any key, we have to provide two parameters i.e., the key alias and password.
char[] keyPassword = “abc123”.toCharArray();
KeyStore.ProtectionParameter entryPassword =
new KeyStore.PasswordProtection(keyPassword);
KeyStore.Entry keyEntry = keyStore.getEntry(“keyAlias”, entryPassword);
GENERATING A SECRET KEY FOR KEYSTORE
You can set the keys in KeyStore by using the setEntry method. This method takes in a password, an alias, and a secret key entry. The following code is used to set keys in KeyStore.
SecretKey secretKey = getSecretKey();
KeyStore.SecretKeyEntry secretKeyEntry =
new KeyStore.SecretKeyEntry(secretKey);
keyStore.setEntry(“keyAlias2”, secretKeyEntry, entryPassword);
STORING THE KEYSTORE
We can store a KeyStore in disk or database for later retrieval. To do this, we use the store() method.
char[] keyStorePassword = “123abc”.toCharArray();
try (FileOutputStream keyStoreOutputStream =
new FileOutputStream(“data/keystore.ks”)) {
keyStore.store(keyStoreOutputStream, keyStorePassword);
}
CONCLUSION
In this article, we have discussed what is KeyStore, how to construct KeyStore, how to load KeyStore, fetching keys from KeyStore, generating secret key and finally storing the KeyStore.





