Tuesday, 7 February 2023

Quick guide to java.security.KeyStore class

Java keystore provides a storage to store the keys, certificates. Following are the java supported keystore file formats.

a.   JKS

b.   JCEKS

c.    PKCS#12

d.   DKS

e.   PCKCS#11

 

File format

Store public, private keys

Store certificates

Store secret keys

JKS

Yes

Yes

No

JCEKS

Yes

Yes

Yes

PKCS#12

Yes

Yes

No

 

All the keystores (JKS, JCEKS, PKCS#12) are protected by a password. To provide further security, each private key or secret key that you are going to store in a keystore is protected by another individual password.

 

In this tutorial series, I am going to explain how to work with a keystore using java.secutiry.KeyStore class.

 

Create a keystore

public static KeyStore createEmptyKeyStore(String keyStoreType, String keyStoreFilePath, String keyStorePassword)
        throws Exception {
    KeyStore keyStore = KeyStore.getInstance(keyStoreType);

    char[] pwdArray = keyStorePassword.toCharArray();
    keyStore.load(null, pwdArray);

    try (FileOutputStream fos = new FileOutputStream(keyStoreFilePath)) {
        keyStore.store(fos, pwdArray);
    }
    return keyStore;
}

Print the entries of keystore

public static void printEntries(KeyStore keyStore) throws KeyStoreException {
    Enumeration<String> aliases = keyStore.aliases();

    while (aliases.hasMoreElements()) {
        String alias = aliases.nextElement();
        System.out.println(alias);
    }
}

Save symmetric key to the key store

public static void saveSymmetricKey(KeyStore keyStore, SecretKey secretKey, String secretKeyAlias,
        String secretKeyPassword) throws KeyStoreException {
    KeyStore.SecretKeyEntry secret = new KeyStore.SecretKeyEntry(secretKey);
    KeyStore.ProtectionParameter password = new KeyStore.PasswordProtection(secretKeyPassword.toCharArray());
    keyStore.setEntry(secretKeyAlias, secret, password);
}

Load existing keystore

public static KeyStore loadExistingKeystore(String keyStoreType, String keyStoreFilePath, String keyStorePassword)
        throws Exception {
    KeyStore keyStore = KeyStore.getInstance(keyStoreType);
    char[] pwdArray = keyStorePassword.toCharArray();
    keyStore.load(new FileInputStream(keyStoreFilePath), pwdArray);
    return keyStore;
}

Get the certificate entry by alias

java.security.cert.Certificate certificate = keyStore.getCertificate("certificate-alias");

Get the key by alias and password

Key key = keyStor.getKey("keyAlias", "keyPassword".toCharArray());

Find the below working application.

 

KeystoreUtil.java

package com.sample.app.util;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.util.Enumeration;

import javax.crypto.SecretKey;

public class KeystoreUtil {

    public static KeyStore createEmptyKeyStore(String keyStoreType, String keyStoreFilePath, String keyStorePassword)
            throws Exception {
        KeyStore keyStore = KeyStore.getInstance(keyStoreType);

        char[] pwdArray = keyStorePassword.toCharArray();
        keyStore.load(null, pwdArray);

        try (FileOutputStream fos = new FileOutputStream(keyStoreFilePath)) {
            keyStore.store(fos, pwdArray);
        }
        return keyStore;
    }

    public static void printEntries(KeyStore keyStore) throws KeyStoreException {
        Enumeration<String> aliases = keyStore.aliases();

        while (aliases.hasMoreElements()) {
            String alias = aliases.nextElement();
            System.out.println(alias);
        }
    }

    public static void saveSymmetricKey(KeyStore keyStore, SecretKey secretKey, String secretKeyAlias,
            String secretKeyPassword) throws KeyStoreException {
        KeyStore.SecretKeyEntry secret = new KeyStore.SecretKeyEntry(secretKey);
        KeyStore.ProtectionParameter password = new KeyStore.PasswordProtection(secretKeyPassword.toCharArray());
        keyStore.setEntry(secretKeyAlias, secret, password);
    }

    public static KeyStore loadExistingKeystore(String keyStoreType, String keyStoreFilePath, String keyStorePassword)
            throws Exception {
        KeyStore keyStore = KeyStore.getInstance(keyStoreType);
        char[] pwdArray = keyStorePassword.toCharArray();
        keyStore.load(new FileInputStream(keyStoreFilePath), pwdArray);
        return keyStore;
    }

}

HelloWorld.java

package com.sample.app;

import java.security.Key;
import java.security.KeyStore;

import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;

import com.sample.app.util.KeystoreUtil;

public class HelloWorld {

    public static void main(String[] args) throws Exception {
        String keyStorePassword = "test123";
        String keyStoreType = "jceks";
        String keyStoreFilePath = "/Users/Shared/demo.jceks";
        String secretKeyAlias = "secretKey1";
        String secretKeyPassword = "test456";

        System.out.println("Creating empty key store : " + keyStoreFilePath);
        KeyStore keyStore = KeystoreUtil.createEmptyKeyStore(keyStoreType, keyStoreFilePath, keyStorePassword);

        System.out.println("Printing the elements of keystore");
        KeystoreUtil.printEntries(keyStore);

        System.out.println("\nAdding new secret key to the keystore");
        KeyGenerator keyGen = KeyGenerator.getInstance("AES");
        keyGen.init(128);
        SecretKey secretKey = keyGen.generateKey();
        KeystoreUtil.saveSymmetricKey(keyStore, secretKey, secretKeyAlias, secretKeyPassword);

        System.out.println("\nPrinting the elements of keystore : " + keyStoreFilePath);
        KeystoreUtil.printEntries(keyStore);

        String existingKeyStore = "/Users/Shared/myKeystore.jks";
        KeyStore loadedkeyStore = KeystoreUtil.loadExistingKeystore("jks", existingKeyStore, "test123");
        System.out.println("\nPrinting the elements of keystore : " + existingKeyStore);
        KeystoreUtil.printEntries(keyStore);
        KeystoreUtil.printEntries(loadedkeyStore);

        System.out.println("\nPrint the certificate");
        java.security.cert.Certificate certificate = loadedkeyStore.getCertificate("java-blogspot");
        System.out.println(certificate);

        System.out.println("\nPrint key information");
        Key key = loadedkeyStore.getKey("myserverkey", "test456".toCharArray());
        System.out.println("Algorithm : " + key.getAlgorithm());
    }

}


 

Previous                                                 Next                                                 Home

No comments:

Post a Comment