Initializing SSLContext with PKCS12 File

This section provides a tutorial example on how to write a simple program to test the java.net.ssl.SSLContext class with a PKCS12 keystore file.



Since JDK 9, the keytool has switched the default keystore file type from "JKS" to "PKCS12". If you have a "PKCS12" keystore file, you will have problems running the test program, SslContextTest.java, presented in the previous tutorial.

To support "PKCS12" keystore files, I have created a new test program, SslContextPkcsTest.java:

/* SslContextPkcsTest.java
 * Copyright (c) HerongYang.com. All Rights Reserved.
 */
import java.io.*;
import java.net.*;
import java.security.*;
import javax.net.*;
import javax.net.ssl.*;
public class SslContextPkcsTest {
   public static void main(String[] args) {
      PrintStream out = System.out;
      out.println("\nTesting socket factory with SSLContext:");
      try {
      	 // SSLContext protocols: TLS, SSL, SSLv3
         SSLContext sc = SSLContext.getInstance("SSLv3");
         System.out.println("\nSSLContext class: "+sc.getClass());
         System.out.println("   Protocol: "+sc.getProtocol());
         System.out.println("   Provider: "+sc.getProvider());

      	 // SSLContext algorithms: SunX509
         KeyManagerFactory kmf 
            = KeyManagerFactory.getInstance("SunX509");
         System.out.println("\nKeyManagerFactory class: "
            +kmf.getClass());
         System.out.println("   Algorithm: "+kmf.getAlgorithm());
         System.out.println("   Provider: "+kmf.getProvider());

      	 // KeyStore types: PKCS12
         String ksName = "herong.pkcs";
         char ksPass[] = "HerongJKS".toCharArray();
         KeyStore ks = KeyStore.getInstance("PKCS12");
         ks.load(new FileInputStream(ksName), ksPass);
         System.out.println("\nKeyStore class: "+ks.getClass());
         System.out.println("   Type: "+ks.getType());
         System.out.println("   Provider: "+ks.getProvider());
         System.out.println("   Size: "+ks.size());

         // Generating KeyManager list
         kmf.init(ks,ksPass);
         KeyManager[] kmList = kmf.getKeyManagers();
         System.out.println("\nKeyManager class: "
            +kmList[0].getClass());
         System.out.println("   # of key manager: " +kmList.length);

         // Generating SSLServerSocketFactory
         sc.init(kmList, null, null);
         SSLServerSocketFactory ssf = sc.getServerSocketFactory();
         System.out.println("\nSSLServerSocketFactory class: "
            +ssf.getClass());
         
         // Genearting SSLServerSocket
         SSLServerSocket ss
            = (SSLServerSocket) ssf.createServerSocket();
         System.out.println("\nSSLServerSocket class: "
            +ss.getClass());
         System.out.println("   String: "+ss.toString());

         // Generating SSLSocketFactory
         sc.init(kmList, null, null);
         SSLSocketFactory sf = sc.getSocketFactory();
         System.out.println("\nSSLSocketFactory class: "
            +sf.getClass());

         // Genearting SSLSocket
         SSLSocket s
            = (SSLSocket) sf.createSocket();
         System.out.println("\nSSLSocket class: "+s.getClass());
         System.out.println("   String: "+s.toString());
      } catch (Exception e) {
         e.printStackTrace();
      }
   }
}

Note that the password for the private key entry (with a self-signed certificate) in a "PKCS12" keystore file is the same as the keystore file password. This is why we have the " kmf.init(ks,ksPass);" statement.

To test this program, you can follow this command to create a new "PKCS12" keystore file with a new private key:

C:\herong>keytool -genkeypair -alias my_home 
   -keystore herong.pkcs -storepass HerongJKS
   
Enter keystore password:  HerongJKS
What is your first and last name?
  [Unknown]:  Herong Yang
What is the name of your organizational unit?
  [Unknown]:  My Unit
What is the name of your organization?
  [Unknown]:  My Home
What is the name of your City or Locality?
  [Unknown]:  My City
What is the name of your State or Province?
  [Unknown]:  My State
What is the two-letter country code for this unit?
  [Unknown]:  US
Is <CN=Herong Yang, OU=My Unit, O=My Home, L=My City, ST=My State, 
   C=US> correct?
  [no]:  yes

If you run this program, you will get:

C:\herong>java SslContextPkcsTest

Testing socket factory with SSLContext:

SSLContext class: class javax.net.ssl.SSLContext
   Protocol: SSLv3
   Provider: SunJSSE version 10

KeyManagerFactory class: class javax.net.ssl.KeyManagerFactory
   Algorithm: SunX509
   Provider: SunJSSE version 10

KeyStore class: class java.security.KeyStore
   Type: PKCS12
   Provider: SUN version 10
   Size: 1

KeyManager class: class sun.security.ssl.SunX509KeyManagerImpl
   # of key manager: 1

SSLServerSocketFactory class: 
   class sun.security.ssl.SSLServerSocketFactoryImpl

SSLServerSocket class: class sun.security.ssl.SSLServerSocketImpl
   String: [SSL: ServerSocket[unbound]]

SSLSocketFactory class: class sun.security.ssl.SSLSocketFactoryImpl

SSLSocket class: class sun.security.ssl.SSLSocketImpl
   String: 587c290d[SSL_NULL_WITH_NULL_NULL: Socket[unconnected]]

There is no problem to initialize a SSLContext object with a PKCS12 file.



 

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

 Secret Key Generation and Management

 Cipher - Encryption and Decryption

The SSL (Secure Socket Layer) Protocol

 What Is SSL (Secure Socket Layer)?

 SSL Specification Overview

 JSSE - Java Implementation of SSL and TLS

 SslSocketTest.java - Default SSL Socket Factory Test

 SslContextTest.java - javax.net.ssl.SSLContext Class Test

Initializing SSLContext with PKCS12 File

 SSL Socket Communication Testing Programs

 SSL Client Authentication

 HTTPS (Hypertext Transfer Protocol Secure)

 Outdated Tutorials

 References

 Full Version in PDF/EPUB