Skip to main content
IBM  
Shop Support Downloads
IBM Home Products Consulting Industries News About IBM
IBM developerWorks : Java : Education - Tutorials
Java security, Part 1: Crypto basics
ZIPPDF (letter)PDF (A4)e-mail
Main menuSection menuFeedbackPreviousNext
9. SSL/TLS: Securing C/S communication
  


SSL/TLS code sample page 3 of 4


In this example, we write an HTTPS daemon process using an SSL server socket that returns an HTML stream when a browser connects to it. This example also shows how to generate a machine certificate in a special keystore to support the SSL deployment.

In Java programming, the only thing that needs to be done is to use an SSL Server Socket Factory instead of a Socket Factory, using lines like the following:

 
SSLServerSocketFacctory sslf = 
  (SSLServerSocketFactor)SSLServerSocketFactory.getDefault();
ServerSocket serverSocket = sslf.createServerSocket(PORT);

The complete code example is listed below:


import java.io.*;
import java.net.*;
import javax.net.ssl.*;
//
// Example of an HTTPS server to illustrate SSL certificate and socket
public class HTTPSServerExample {

  public static void main(String[] args) throws IOException {

    //
    // create an SSL socket using the factory and pick port 8080
    SSLServerSocketFactory sslsf =
      (SSLServerSocketFactory)SSLServerSocketFactory.getDefault();
    ServerSocket ss = sslsf.createServerSocket(8080);
    //
    // loop forever
    while (true) {
      try {
        //
        // block waiting for client connection
        Socket s = ss.accept();
        System.out.println( "Client connection made" );
        // get client request
        BufferedReader in = new BufferedReader(
          new InputStreamReader(s.getInputStream()));
        System.out.println(in.readLine());
        //
        // make an HTML response
        PrintWriter out = new PrintWriter( s.getOutputStream() );
        out.println("<HTML><HEAD><TITLE>HTTPS Server Example</TITLE>" +
                    "</HEAD><BODY><H1>Hello World!</H1></BODY></HTML>\n");
        //
        // Close the stream and socket
        out.close();
        s.close();
      } catch (Exception e) {
          e.printStackTrace();
      }
    }
  }
}

Main menuSection menuFeedbackPreviousNext
About IBM | Privacy | Legal | Contact