Let’s Encrypt with Tomcat 7

Using HTTPS on Tomcat with a let’s encrypt certificate is quite easy – as soon as you know how to do it (as usual). acme.sh provides a quite convenient way of getting and renewing certificates. This is extremely important as the certificates have a lifetime of just 60 days.

So get and “install” acme.sh first! And make sure Tomcat is running on port 80. Then start getting your certificate:

sudo service tomcat7 stop
acme.sh --issue -d yourdomain.tld -d www.yourdomain.tld --standalone --httpport 80 --force
sudo service tomcat7 start

You should now have brand new certificates on your machine. Now setup the keystore for Tomcat.

# generate keystore
keytool -genkey -alias tomcat -keyalg RSA -keystore .keystore -keysize 2048
# remember the password you set here. let's assume 'mypass'
	
keytool -importkeystore -srckeystore .keystore -destkeystore .keystore -deststoretype pkcs12

# use the following lines also to renew a certificate!!
certdir=/home/.../.acme.sh/yourdomain.tld
keystoredir=.keystore

keytool -delete -alias tomcat -storepass mypass -keystore $keystoredir
keytool -delete -alias root   -storepass mypass -keystore $keystoredir

openssl pkcs12 -export -in $certdir/fullchain.cer -inkey $certdir/yourdomain.tld.key -out $certdir/cert_and_key.p12 -name tomcat \
        -CAfile $certdir/fullchain.pem -caname root  -password pass:mypass
keytool -importkeystore -srcstorepass mypass -deststorepass mypass -destkeypass mypass -srckeystore $certdir/cert_and_key.p12 \
        -srcstoretype PKCS12 -alias tomcat -keystore $keystoredir
keytool -import -trustcacerts -alias root -deststorepass mypass -file $certdir/fullchain.cer -noprompt -keystore $keystoredir

The keystore should be ready now. Now let us tell Tomcat to use this keystore for HTTPS. Edit /etc/tomcat7/server.xml and apply the following changes to the Connector for 8443:

<Connector port="8443" protocol="org.apache.coyote.http11.Http11Protocol" maxThreads="150" SSLEnabled="true" scheme="https" secure="true" clientAuth="false" sslProtocol="TLS" KeystoreFile="/home/.../.keystore" KeystorePass="mypass" ciphers="TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384, TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,TLS_ECDHE_RSA_WITH_RC4_128_SHA, TLS_RSA_WITH_AES_128_CBC_SHA256,TLS_RSA_WITH_AES_128_CBC_SHA, TLS_RSA_WITH_AES_256_CBC_SHA256,TLS_RSA_WITH_AES_256_CBC_SHA, SSL_RSA_WITH_RC4_128_SHA" />

You should be done now. Now just restart Tomcat and test the certificate in the browser.  If all is fine, don’t forget to schedule a cron job to refresh the certificate and execute the steps above of removing and adding the certificate to the keystore.

sudo service tomcat7 stop
"/home/.../.acme.sh"/acme.sh --cron --home "/home/.../.acme.sh"
sudo service tomcat7 start
# perform the commands above to insert the renewed certificates!