Introduction to Java KeyStore
Keystore is a database in Java; it allows us to store data in key formats; Keystore is extended from the java class called java.security.KeyStore class, we can write keyStore on the disk and read it from the disk itself, the main benefit of using keyStore in java is it allows us to protect data as it has the feature of storing data in the form of protection with a password and these passwords are their own passwords because these kinds of storing features it makes the best for handling the cases where we need to implement encryption and decryption mechanism.
How to Create a Keystore in Java?
Before going to create a Keystore, we need to understand its types; there are some types of keys mechanisms are available keyStore they are, public keys(this key generally contains an associated certificate which is public in nature), private and public (used for any asymmetric types of encryption). We can use the method getInstance() of the java to create a Keystore in Java. This method is the inbuilt method defined in the main class and which we have exceeded. Below is an example to create a default KeyStore type in java . I am saying it as default because we are not passing any params in the function. In case if we want to create any custom keyStore, then we can pass the argument in the method for our required types of Keystore.
KeyStore customKeyStore = KeyStore.getInstance(custom-format);
Here we can pass custom-format = PKCS12
Example
Code:
Below is an example to create a store using method getInstance():
import java.io.FileInputStream;
import java.security.KeyStore;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
public class KeyCreate {
public static void main(String args[]) throws Exception {
//Creation of Keystore
KeyStore ks = KeyStore.getInstance("JCEKS");
System.out.println("Key Store Created");
}
}
Output:
How to Load Keystore in Java?
Here, loading is an important mechanism for key stores if we talk about the loading section of the Keystore. We need to be careful while performing this operation as it should only load when it is needed. Loading is important because we can not be able to use Keystore without loading it. It is possible to load the Keystore with any empty data also. In general, we can load the Keystore either from any file or from any other storage. There is a method called load(); this method will perform the task of loading of the data. We can pass two attributes to the load method; the attributes are
- InputStream: This is the input stream from where the data will be read; the stream can come from any file or from some other sources.
- Char []: This section is for the security part; here, we can pass a string for KeyStore password for encryption.
Let us understand the basic flow for loading KeyStore.load(dataStream ,password).Here we can take inputStream as the dataStream and any string for the password. As we have mentioned that we can also load the empty data for KyeStore, which we can do by passing any null value for the dataStream of the keyStore like KeyStore.load(null, Keystore password).Once we passed the null as the data stream, it will take a null value and create an empty Keystore for us. An important thing about the keyStore if we do not load the keyStore, it will throw an exception for any method we will call on it. For better coding practice also it is very important to load the keyStore before start using it.
Example
In the below example, we are loading a Keystore with a null value.
Code:
import java.io.FileInputStream;
import java.security.KeyStore;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
public class KeyLoad {
public static void main(String args[]) throws Exception {
//Creation of Keystore
KeyStore ks = KeyStore.getInstance("JCEKS");
ks.load(null);
System.out.println("Loading of an empty Keystore done");
}
}
Output:
How to store Keystore in Java?
We have a lot of discussion of loading and creating the KeyStore in java; let us now focus on the storing. Here storing means data that we want to store for future uses, so the storing can be performed on any places, either on the database or on the disk, dependents on our choices. We have a method called the store which will play the role of storing the data to KeyStore.We can pass two attributes to the KeyStore store() method. Below is the simple syntax example for it.
Syntax
keyStore.store(streamOfOutputData ,password);
Here the stream of streamOfOutputData can be read data from any path and file, and password is the string password for encryption of our stored data. If we need the data which we have stored in the future, we can retrieve them from stored places by loading them again.
Example
Code:
import java.io.FileInputStream;
import java.security.KeyStore;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
public class KeyStoreExample {
public static void main(String args[]) throws Exception {
//Creation of Keystore
KeyStore ks = KeyStore.getInstance("JCEKS");
//Loading the KeyStore object
char[] ps = "ranjan".toCharArray();
String filePath = "./cacerts";
java.io.FileInputStream streamInput = new FileInputStream(filePath);
ks.load(null);
KeyStore.ProtectionParameter pp = new KeyStore.PasswordProtection(ps);
//Here we are creating an secret object
SecretKey ms = new SecretKeySpec("anypassword".getBytes(), "DSA");
//Creating SecretKeyEntry object
KeyStore.SecretKeyEntry ske = new KeyStore.SecretKeyEntry(ms);
ks.setEntry("secretKeyAlias", ske, pp);
//Storing the object
java.io.FileOutputStream storeData = null;
storeData = new java.io.FileOutputStream("nameOfNewKey");
ks.store(storeData, ps);
System.out.println("data stored");
}
}
Output:
How to get and set Keys?
We can use two methods called getKey and setKey to get and set the keys. These methods are part of the KeyStore in java. The method getEntry will allow us to get the value stored. Note that we have stored the value on the key with a password, so we need to pass the alias name of the key and the password which used for storing the key. In a similar way, we have a method called setKeyEntry.After getting the value from the keyStore again we can access the data with various available method like getPrivateKey(),getcertificate() ,getPrivateKey() and getCertificateChain() .These methods can be used to get the data according to our requirement from the keyStore.
Example
In the below example, we are checking if the key is available or not from any keyStore.
Code:
import java.security.*;
import java.security.cert.*;
import java.util.*;
import java.io.*;
public class SetAndGetKey {
public static void main(String[] argv)
{
try {
KeyStore store = KeyStore.getInstance("JCEKS");
store.load(null);
Boolean status
= store.isKeyEntry("test");
if (status)
System.out.println("The key available");
else
System.out.println("The key is not available");
}
catch (NoSuchAlgorithmException e) {
//catch code to handle exception
}
catch (NullPointerException e) {
//catch code to handle exception
}
catch (KeyStoreException e) {
//catch code to handle exception
}
catch (FileNotFoundException e) {
//catch code to handle exception
}
catch (IOException e) {
//catch code to handle exception
}
catch (CertificateException e) {
//catch code to handle exception
}
}
}
Output:
Java Keystore Methods
To perform various operations on the KeyStore, we have various methods they are given below.
- load(inputStream, password): It will load the keyStore data, and it needs two parameters, one as the input stream(file or any disk data) and password of string
- store(outputStream, password): This method will be used for storing the data, and it will take two params one is output stream which from where data is going to read it could be file or disk and the second parameter is the password which will encrypt the data which we are storing.
- getInstance(): This method is used to create a keyStore; if we pass nothing to this method, then it will create default keyStore else, we can pass PKCS12 as the type of the keyStore.
- getPrivateKey(): After getting keyStore, we can fetch private keys with this method.
- getCertificate(): To get the certificates, we can use this method.
- getCertificateChain(): If we wanted to get a chain of certificates, we can use this method.
Conclusion
From this tutorial, we learned the basic concept of KeyStore in Java, and we learned about the creation, loading, and getting various types of data from the Keystore data; we learned about the various available methods and their uses in java for KeyStore.
Recommended Articles
This is a guide to Java KeyStore. Here we discuss an introduction, syntax, and a complement guide on Keystore in java. You can also go through our other related articles to learn more –
41 Online Courses | 29 Hands-on Projects | 305+ Hours | Verifiable Certificate of Completion
4.8
View Course
Related Courses