Search code examples
javasslkeystore

Explain the code - SSL


Can any one please explain the below code (labeled "HERE").

  1. Keystore.load() performs what?
  2. Why KeyManagerFactory is used?

I need practical oriented solution.

System.setProperty("1", "/Library/Java/JavaVirtualMachines/jdk1.8.0_51.jdk/Contents/Home/jre");

String jrehome = System.getProperty("1");
String path = jrehome + "/" + "lib" + "/" + "security" + "/" + "cacerts";
char[] ksPass= "changeit".toCharArray();

try {
    KeyStore ks = KeyStore.getInstance("JKS"); // <- HERE
    System.out.println(ks.toString());
    ks.load(new FileInputStream(path), ksPass);

    KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
    kmf.init(ks, ksPass);

    TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509");
    System.out.println(ks.getCertificate("SunX509"));
    tmf.init(ks);

    SSLContext sc = SSLContext.getInstance("TLS");
    sc.getClientSessionContext().setSessionCacheSize(1);
    sc.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
    SSLServerSocketFactory ssf = sc.getServerSocketFactory();

    SSLServerSocket s = (SSLServerSocket) ssf.createServerSocket(8888); // <-- HERE

    System.out.println("Server started:");
}

Solution

    1. Keystore.load() is a mandatory call for accessing a keystore else you cannot acces it. The Javadoc says so. Once the keystore has been loaded, it is possible to read existing entries from the keystore, or to write new entries into the keystore. You have some overloaded method for load().

    2. KeyManagerFactory is a class that follows Factory pattern which creates Key Manager instances for managing a specific type of key material for use by secure sockets.