Updated July 5, 2023
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 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. These passwords are their passwords because these kinds of storing features make the best for handling the cases where we need to implement encryption and decryption mechanism.
How to Create a KeyStore in Java?
Before creating a Keystore, we need to understand its types; there are some key mechanisms available keyStore are public keys(this key generally contains an associated certificate that is public), private, and public (used for any asymmetric types of encryption). We can use the method getInstance() of 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 of creating a default KeyStore type in Java. I am saying it as default because we are not passing any params in the function. If we want to create any custom keyStore, 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
Below is an example of creating a store using the method getInstance().
Code:
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 must be careful while performing this operation, as it should only load when needed. Loading is important because we can not 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 the data. We can pass two attributes to the load method; the attributes are
- InputStream: This is the input stream from which the data will be read; the stream can come from any file or other source.
- Char []: This section is for security; here, we can pass a string for the 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, 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 pass 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 is that if we do not load the KeyStore, it will throw an exception for any method we call on. 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 about loading and creating the KeyStore in Java; let us now focus on storing. Here storing means data that we want to store for future uses, so the storing can be performed anywhere, either on the database or the disk, depending on our choices. We have a method called the store which will play the role of storing the data in KeyStore.We can pass two attributes to the KeyStore store() method. Below is a simple syntax example for it.
Syntax
keyStore.store(streamOfOutputData ,password);
Here the stream of streamOfOutputData can read data from any path and file, and the password is the string password for the encryption of our stored data. If we need the data 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 used for storing the key. Similarly, we have a method called setKeyEntry.After getting the value from the keyStore again, we can access the data with various available methods like getPrivateKey(),getcertificate(),getPrivateKey(), and getCertificateChain(). These methods can be used to get the data according to our requirements from the KeyStore.
Example
In the example below, we check if the key is available 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 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 a default keyStore else, we can pass PKCS12 as the keyStore type.
- getPrivateKey(): After getting keyStore, we can fetch private keys with this method.
- getCertificate(): We can use this method to get the certificates.
- getCertificateChain(): If we want 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 about the creation, loading, and getting of various types of data from the Keystore data; we learned about the various available methods and their uses in Java for KeyStore.
Recommended Articles
We hope that this EDUCBA information on “Java KeyStore” was beneficial to you. You can view EDUCBA’s recommended articles for more information.