How to pass your custom truststore as argument to JVM when running a jar file
Overview
When a client requests some information from a server using the HTTPS protocol, a SSL connection is established using a SSL protocol. The SSL protocol includes 2 subprotocols, SSL Handhake is one of them.
During a SSL Handshake, among many other things, the client authenticates the identity of the server using the server’s public key and SSL certificate.
In this article, we will assume that the developer has several SSL certificates and wants to tell JVM to use their custom truststore instead of Java’s default cacerts
Create a custom truststore using keytool command
This creates an empty truststore, it will ask for some of the details and its up to you to fill out the information.
keytool -genkey -alias exampletruststore -keyalg RSA -keystore mytruststore.jks
Import a certificate to custom truststore using Java keytool command
Here is how to import a certificate that is already present on your computer:
keytool -import -alias example -file example.cer -keystore mytruststore.jks -storepass changeit
Note that changeit is the default password and can be changed.
List all certificates in trusstore
keytool -list -keystore mytruststore.jks
Use -v between -list and -keystore to get more information on the certificates.
Run jar file with custom truststore instead of Java default truststore (cacerts)
Now to the main part, suppose you have a jar file running on a server, instead of putting all the certificates into Java’s default cacerts ($JAVA_HOME/jre/lib/security/cacerts), add your mytruststore.jks to some location on the server and tell JVM to use your custom truststore, below is the code-
java -Djavax.net.ssl.trustStore=/some/loc/on/server/ mytruststore.jks -Djavax.net.ssl.trustStorePassword=changeit -jar run.jar
Thats it and now the JVM on server will be using your custom truststore.