Recipe 17.6 Securing a Web Server with SSL and JSSE


You want to protect your network traffic from prying eyes or malicious modification, while the data is in transit.


Use the Java Secure Socket Extension, JSSE, to encrypt your traffic.


Introduced in JDK 1.4, JSSE provides services at a number of levels, but the simplest way to use it is simply to get your ServerSocket from an SSLServerSocketFactory instead of using the ServerSocket constructor directly. SSL is the Secure Sockets Layer; a revised version is known as TLS. It is specific to use on the Web. To secure other protocols, you'd have to use a different form of the SocketFactory.

The SSLServerSocketFactory returns a ServerSocket that is set up to do SSL encryption. The code in Example 17-9 uses this technique to override the getServerSocket( ) method in Recipe Recipe 17.5. If you're thinking this is too easy, you're wrong!

Example 17-9. JSSEWebServer0
import; import; /**  * JSSEWebServer - subclass trivial WebServer0 to make it use SSL.  * @version $Id: ch17.xml,v 1.4 2004/05/04 18:04:5 ian Exp $  */ public class JSSEWebServer0 extends WebServer0 {     public static final int HTTPS = 8443;          public static void main(String[] args) throws Exception {         System.out.println("DarwinSys JSSE Server 0.0 starting...");         JSSEWebServer0 w = new JSSEWebServer0(  );         w.runServer(HTTPS);        // never returns!!     }          /** Get an HTTPS ServerSocket using JSSE.      * @see WebServer0#getServerSocket(int)      * @throws ClassNotFoundException if the SecurityProvider cannot be instantiated.      */     protected ServerSocket getServerSocket(int port) throws Exception {                  SSLServerSocketFactory ssf = (SSLServerSocketFactory)SSLServerSocketFactory. getDefault(  );                  return ssf.createServerSocket(port);     } }

That is, indeed, all the Java code one needs to write. You do have to set up a Web Server Certificate. For demonstration purposes, this can be a self-signed certificate; the steps in Recipe Recipe 23.14 (Steps 1-4) will suffice. You have to tell the JSSE layer where to find your keystore:

java keyStorePassword=secrit JSSEWebServer0

The typical client browser raises its eyebrows at a self-signed certificate (see Figure 17-1), but, if the user OKs it, will accept the certificate. Figure 17-2 shows the output of the simple WebServer0 being displayed over the HTTPS protocol (notice the padlock in the lower right corner).

Figure 17-1. Browser caution

Figure 17-2. With encryption

See Also

JSSE can do much more than encrypt web server traffic; this is, however, sometimes seen as its most exciting application. For more information on JSSE, see the Sun web site or Java Security by Scott Oaks (O'Reilly).

Java Cookbook
Java Cookbook, Second Edition
ISBN: 0596007019
EAN: 2147483647
Year: 2003
Pages: 409
Authors: Ian F Darwin

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: