Skip to main content

Java SSL Sockets

Posted by evanx on May 28, 2007 at 10:45 PM PDT

Let's build a trivial client/server demo using SSLServerSocket and SSLSocket as provided by the Java Secure Socket Extension (JSSE). We create a self-signed public key certificate for the server using keytool, and install this on the client.

Code Snippet

We implement the client as follows.

public class EnigmaClient extends Thread {
    EnigmaSocket enigmaSocket;
    KeyStore keyStore;
    KeyManager[] keyManagers;
    TrustManager[] trustManagers;
    SSLContext sslContext;
    public void init() throws Exception {
    public void connect(String host, int port) throws Exception {
        SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
        Socket clientSocket = sslSocketFactory.createSocket(host, port);
        this.enigmaSocket = new EnigmaSocket(clientSocket);

where the keystore containing the server's digital certificate eg. created using keytool, is loaded from a resource or file, and a KeyManagerFactory and TrustManagerFactory are initialised with the keyStore instance. Finally, an SSLContext is initialised with key managers and trust managers, and this is used to create SSL socket connections.