Sunday, 10 June 2012

Java SSL threaded echo server


I'm busy playing around with Java and put together the following SSL server, the client side needs to be SSL enabled too. Currently it echo's back everything received in the thread handling the client...

To create the keystore: keytool -genkey -keystore KeyStoreName -keyalg RSA

To compile the source code: javac SSL.javac

To run the server: java -Djavax.net.ssl.keyStore=KeyStoreName
-Djavax.net.ssl.keyStorePassword=123456 SSL

To debug add: -Djava.protocol.handler.pkgs=com.sun.net.ssl.internal.www.protocol -Djavax.net.debug=ssl

File SSL.java contents:

import java.io.*;
import javax.net.*;
import javax.net.ssl.*;
import java.security.*;

class ClientHandler implements Runnable {

 SSLSocket socket;
 ClientHandler (SSLSocket socket) {
  this.socket = socket;
  Thread thread = new Thread(this);
  thread.setDaemon(true);
  thread.start();
 }

 public void run() {
  System.out.println("Client be served:");
  try {
   BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
   PrintWriter out = new PrintWriter(socket.getOutputStream());
   String inputLine, outputLine;
   while ((inputLine = in.readLine()) != null) {
    outputLine = inputLine;
    out.println(outputLine);
    out.flush();
   }
   System.out.println("Client disconnected");           
   out.close();
   in.close();
   socket.close();
  } catch(Exception e) {
   System.out.println("Error encountered -> "+e);
  }
 }
}
   
public class SSLserver {
 public static void main(String[] args) {
  try {
   SSLServerSocketFactory sslserversocketfactory = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
   SSLServerSocket sslserversocket = (SSLServerSocket) sslserversocketfactory.createServerSocket(443);//Port, we chose the default for https

   //Configure the ciphers/protocols to use
   //String [] ciphers = new String [] { "SSL_RSA_WITH_DES_CBC_SHA" };//If you wish to limit ciphers
   String [] protocols = new String [] { "SSLv3" };

   //sslserversocket.setEnabledCipherSuites(ciphers);
   sslserversocket.setEnabledProtocols(protocols);

   for(;;){
    SSLSocket client = (SSLSocket) sslserversocket.accept();
    new ClientHandler(client);
   }
  } catch(Exception e) {
   System.out.println("Error encountered -> "+e);
  }
 }
}


1 comment:

  1. Hi - I just wanted to say "THANKS!" for this. I've been looking for a good example of a Java SSL/HTTPS server and yours is the one that worked for me.

    ReplyDelete