Securing Tomcat (Java)

The first step to enabling SSL on Tomcat is to generate a keystore and a key with the keytool utility. This utility comes with the Java development environment, and has a multitude of different flags and options. For this article, I'm going to limit my discussion to the creation and viewing of a key/keystore. (For a more complete coverage of keytool, you may want to read this: http://docs.oracle.com/javase/7/docs/technotes/tools/solaris/keytool.html ).

Fist, navigate to an appropriate directory - perhaps to the tomcat config directory. Once there, the basic command for creating a key and keystore is as follows:
keytool -genkey -alias fishing -keyalg RSA -keystore fishing.keystore

After entering this command, you'll be prompted for some additional information. This information is captured in the following diagram:

NOTE: In the above example, I changed the algorithm to RSA. I did this because the default algorithm will not work with iOS devices. (Thank you stackoverflow.com for helping me with this one!)

At this point it's time to update one of Tomcat's configuration files: server.xml. If you're using Eclipse, expand the list of servers in the Package Explorer, and double click on server.xml. If you're running tomcat from the command line, the file will be located in the conf directory under your tomcat installation. Near the bottom, add the following:

  1. <Connector SSLEnabled="true" clientAuth="false"
  2. keystoreFile="/path/to/my/keystore/fishing.keystore"
  3. keystorePass="mypassword" maxThreads="150" port="8443"
  4. protocol="HTTP/1.1" scheme="https" secure="true" sslProtocol="TLS"/>

Once this is saved, launch tomcat, and attempt to connect on port 8443. For example: https://localhost:8443/fishingserver/locations.json?action=list&userid=tcrowley&token=12&id=65. At first, you should see a dire warning similar to the following:

This is a good thing. I self-signed this certificate, so my browser is stating that the connection can't be trusted. Since I'm visiting my own site, I'll click 'Proceed anyway'. Upon doing so, I'll see this:

This shows that I successfully retrieved encrypted results - even if the connection isn't a trusted connection.

This completes the configuration of HTTPS under Tomcat.