Different types of keystore in Java -- JCEKS

English 简体中文 繁体中文 ภาษาไทย Tiếng Việt
Summary

JCEKS, or Java Cryptography Extension KeyStore, provides an alternative format for securely storing encryption keys and certificates within Java applications. Its operational flow for managing entries closely resembles JKS, primarily differing by requiring "JCEKS" when initializing a KeyStore instance. A key focus is on securely handling secret keys, which are sealed and protected by a password within the keystore. Developers can store a generated secret key using `keyStore.setKeyEntry()` and persist it, then later retrieve it with `keyStore.getKey()` for use in cryptographic operations. This approach helps prevent the exposure of sensitive key data.

JCEKS stands for Java Cryptography Extension KeyStore and it is an alternative keystore format for the Java platform. Storing keys in a KeyStore can be a measure to prevent your encryption keys from being exposed. Java KeyStores securely contain individual certificates and keys that can be referenced by an alias for use in a Java program.

The process of storing and loading different entries in JCEKS is similar to what JKS does. So please refer to the article Different types of keystore in Java -- JKS. Change the keystore type from JKS to JCEKS accordingly when calling KeyStore.getInstance().

In this post, we will only cover the process of storing secret keys in JCEKS keystore. The secret key entry will be sealed and stored in the keystore to protect the key data. Please provide a strong password when storing the entry into the keystore.

Store secret key

The secret key can be stored in JCEKS keystore with below code.

try{
	KeyStore keyStore = KeyStore.getInstance("JCEKS");
	keyStore.load(null, null);
	
	KeyGenerator keyGen = KeyGenerator.getInstance("DES");
	keyGen.init(56);;
	Key key = keyGen.generateKey();
	
	keyStore.setKeyEntry("secret", key, "password".toCharArray(), null);
	
	keyStore.store(new FileOutputStream("output.jceks"), "password".toCharArray());
} catch (Exception ex) {
	ex.printStackTrace();
}

Load secret key

The stored secret key can be extracted from JCEKS keystore in Java. The extracted key can be used to encrypt/decrypt data as normal.

try{
	KeyStore keyStore = KeyStore.getInstance("JCEKS");
	keyStore.load(new FileInputStream("output.jceks"), "password".toCharArray());
	
	Key key = keyStore.getKey("secret", "password".toCharArray());
	
	System.out.println(key.toString());
} catch (Exception ex) {
	ex.printStackTrace();
}

The output is :

javax.crypto.spec.SecretKeySpec@fffe7b9b

For the different types of keystores, please refer to Different types of keystore in Java -- Overview.

JAVA TUTORIAL KEYSTORE JCEKS

  RELATED

  COMMENT

1
Anonymous
Mar 4, 2021 at 3:02 pm

why using "password" twice just after you said "please use strong password" :(