JcaKeyStoreTest.java - 'keystore' Class Test Program

This section provides a tutorial example on how to write a sample program to use the 'keystore' class to open a 'keystore' database file. The sample program also exports one certificate out of the 'keystore' object.

The following sample program shows you how to load a keystore database from a file into a KeyStore object, extracting a certificate from the keystore into a certificate file, then importing the certificate back into the keystore.

/* JcaKeyStoreTest.java
 * Copyright (c) HerongYang.com. All Rights Reserved.
 */
import java.io.*;
import java.util.*;
import java.security.*;
import java.security.cert.*;
class JcaKeyStoreTest {
   public static void main(String[] a) {
      if (a.length<3) {
         System.out.println("Usage:");
         System.out.println("java JcaKeyStoreTest store sPass alias");
         return;
      }
      String store = a[0];
      String sPass = a[1];
      String alias = a[2];
      try {
         test(store,sPass,alias);
      } catch (Exception e) {
         System.out.println("Exception: "+e);
         return;
      }
   }
   private static void test(String store, String sPass, String alias)
      throws Exception {
      // KeyStore ks = KeyStore.getInstance("JKS");
      KeyStore ks = KeyStore.getInstance("PKCS12");
      System.out.println();
      System.out.println("KeyStore Object Info: ");
      System.out.println("Type = "+ks.getType());
      System.out.println("Provider = "+ks.getProvider());
      System.out.println("toString = "+ks.toString());

      FileInputStream fis = new FileInputStream(store);
      ks.load(fis,sPass.toCharArray());
      fis.close();
      System.out.println();
      System.out.println("KeyStore Content: ");
      System.out.println("Size = "+ks.size());
      Enumeration e = ks.aliases();
      while (e.hasMoreElements()) {
         String name = (String) e.nextElement();
         System.out.print("   "+name+": ");
         if (ks.isKeyEntry(name)) System.out.println(" Key entry");
         else System.out.println(" Certificate entry");
      }

      java.security.cert.Certificate cert = ks.getCertificate(alias);
      System.out.println();
      System.out.println("Certificate Object Info: ");
      System.out.println("Type = "+cert.getType());
      System.out.println("toString = "+cert.toString());

      FileOutputStream fos = new FileOutputStream(alias+".crt");
      byte[] certBytes = cert.getEncoded();
      fos.write(certBytes);
      fos.close();

      CertificateFactory cf = CertificateFactory.getInstance("X.509");
      System.out.println();
      System.out.println("CertificateFactory Object Info: ");
      System.out.println("Type = "+cf.getType());
      System.out.println("Provider = "+cf.getProvider());
      System.out.println("toString = "+cf.toString());

      fis = new FileInputStream(alias+".crt");
      cert = cf.generateCertificate(fis);
      ks.setCertificateEntry(alias+ks.size(),cert);
      fis.close();

      fos = new FileOutputStream(store);
      ks.store(fos,sPass.toCharArray());
      fos.close();
   }
}

Note that JDK switched default keystore file type to "PKCS12" from "JKS" in JDK 9. As of JDK 12 both file types are supported. Basically, you can use KeyStore.getInstance("PKCS12") or KeyStore.getInstance("JKS") to read both keystore file types.

Here is the result of my first test. It uses the key store file generated from the "keytool" command. See the previous chapter for details.

herong> java JcaKeyStoreTest herong.jks HerongJKS my_home

KeyStore Object Info:
Type = PKCS12
Provider = SUN version 10
toString = java.security.KeyStore@1ae369b7

KeyStore Content:
Size = 4
   my_home_2:  Certificate entry
   my_home:  Key entry
   his_home:  Key entry
   my_copy:  Key entry

Certificate Object Info:
Type = X.509
toString = [
[
  Version: V1
  Subject: CN=Herong Yang, OU=My Unit, O=My Home, L=My City, ST=My...
  Signature Algorithm: SHA1withDSA, OID = 1.2.840.10040.4.3
  Key:  Sun DSA Public Key
    Parameters:DSA
...
  Issuer: CN=Herong Yang, OU=My Unit, O=My Home, L=My City, ST=My ...
  SerialNumber: [    407928a4 ]
]
  Algorithm: [SHA1withDSA]
  Signature:
0000: 30 2C 02 14 38 CC 05 0E   3D 67 B5 C1 D8 B0 C9 EF  0,..8...=...
0010: 57 0E C5 4F 70 A4 B5 C7   02 14 59 37 68 93 A4 48  W..Op.......
0020: 79 E0 8C 44 8C AD 2B 07   13 3A 8E FF AA 93        y..D..+.....
]

CertificateFactory Object Info:
Type = X.509
Provider = SUN version 10
toString = java.security.cert.CertificateFactory@3ab50a

Note that the extracted certificate is imported back into the key store a new certificate entry. You can see the new entry, my_home4, if you run the program again:

herong> java JcaKeyStoreTest herong.jks HerongJKS my_home

KeyStore Object Info:
Type = JKS
Provider = SUN version 10
toString = java.security.KeyStore@6ec612

KeyStore Content:
Size = 5
   my_home_2:  Certificate entry
   my_home4:  Certificate entry
   my_home:  Key entry
   his_home:  Key entry
   my_copy:  Key entry

Certificate Object Info:
...

Table of Contents

 About This JDK Tutorial Book

 JDK (Java Development Kit)

 Java Date-Time API

 Date, Time and Calendar Classes

 Date and Time Object and String Conversion

 Number Object and Numeric String Conversion

 Locales, Localization Methods and Resource Bundles

 Calling and Importing Classes Defined in Unnamed Packages

 HashSet, Vector, HashMap and Collection Classes

 Character Set Encoding Classes and Methods

 Character Set Encoding Maps

 Encoding Conversion Programs for Encoded Text Files

 Java Logging

 Socket Network Communication

 Datagram Network Communication

 DOM (Document Object Model) - API for XML Files

 SAX (Simple API for XML)

 DTD (Document Type Definition) - XML Validation

 XSD (XML Schema Definition) - XML Validation

 XSL (Extensible Stylesheet Language)

 Message Digest Algorithm Implementations in JDK

 Private key and Public Key Pair Generation

 PKCS#8/X.509 Private/Public Encoding Standards

 Digital Signature Algorithm and Sample Program

 "keytool" Commands and "keystore" Files

KeyStore and Certificate Classes

 java.security.cert.Certificate - The Certificate Class

 Using CertificateFactory Class to Read in Certificates

 Reading and Writing Certificates in DER and RFC Formats

 java.security.KeyStore - The 'keystore' Class

JcaKeyStoreTest.java - 'keystore' Class Test Program

 Secret Key Generation and Management

 Cipher - Encryption and Decryption

 The SSL (Secure Socket Layer) Protocol

 SSL Socket Communication Testing Programs

 SSL Client Authentication

 HTTPS (Hypertext Transfer Protocol Secure)

 Outdated Tutorials

 References

 Full Version in PDF/EPUB