Tomcat: Enabling SSL

Usually, when you get your SSL certificates, they are .crt, .key, and .ca-bundle files. These work fine for Apache’s HTTP server, but Apache’s Tomcat server needs these converted into a .jks (Java Key Store), and the Tomcat configuration set up to use that key store. To simplify the conversion, here is a shell script to perform the steps, under the assumption that the .crt, .key, and .ca-bundle files all have the same prefix.

#!/bin/sh
if [ "$1" = "" ]; then
  echo ""
  echo "  usage: $0 <file-prefix> <password>"
  echo ""
  echo "  This tool requires that all files have the same prefix, and the .crt, .key, and .ca-bundle files exist."
  echo ""
  echo "  For example, if your files are named example.com.crt, example.com.key, example.com.ca-bundle, you would do:"
  echo ""
  echo "    $0 example.com mySekretPasswd"
  echo ""
  exit 1
fi
echo ""
echo "  Generating JKS file for $1..."
echo ""
echo "----------------------------------------------------------"
openssl pkcs12 -export -in $1.crt -inkey $1.key -name $1 -out $1.p12 -passout pass:$2
keytool -importkeystore -deststorepass $2 -destkeystore $1.jks -srckeystore $1.p12 -srcstoretype PKCS12 -srcstorepass $2
keytool -import -alias bundle -trustcacerts -file $1.ca-bundle -keystore $1.jks -storepass $2
prefix_alias=`keytool -list -v -keystore $1.jks -storepass $2 | grep -i alias | grep $1`
if [ "$prefix_alias" = "" ]; then
  echo ""
  echo "  ** something seems to have gone wrong, $1 not found in aliases"
  echo ""
  exit 1
fi
echo "----------------------------------------------------------"
echo ""
echo "  JKS file created."
echo ""
echo "  Copy $1.jks to Tomcat's ssl directory, typically something like /etc/tomcat8/ssl/$1.jks"
echo ""
echo "  Add or Update the <Connector> entries in Tomcat's server.xml to be something like:"
echo ""
echo "    <Connector port=\"8443\" protocol=\"org.apache.coyote.http11.Http11NioProtocol\" maxThreads=\"150\" SSLEnabled=\"true\" scheme=\"https\" secure=\"true\" clientAuth=\"false\" sslProtocol=\"TLS\" keystoreFile=\"/etc/tomcat8/ssl/$1.jks\" keystoreType=\"JKS\" keystorePass=\"$2\" keyAlias=\"$1\" />"
echo "    <Connector port=\"8009\" protocol=\"AJP/1.3\" redirectPort=\"8443\" />"
echo "" 

An example of using the tool, if your certificate files all start with example.com:

./convert-for-tomcat.sh example.com mySekretPasswd