Add Root Certificate to Java Keystore

2019-02-22 - Shows how to add root certificate to java keystore

SSL Certificates

It certainly happened to you that you want to use your Java-based application to connect to some https resource which doesn't have a valid or trusted certificate. While https and SSL certificates are used to make sure that the site you connect to is trusted, sometimes you may want to override that settings and proclaim that the site with the given (self signed, invalid, …) certificate is secure.

This can be done quite easy by adding that certificate to the Java certificate trust store.

All you need is a keytool command that comes with the Java Development Kit and the certificate.

The easiest way to get the actual certificate is to open the https url in your browser and export certificate from there into the cert1.cer file.

Then all you need is to execute the following command:

keytool -import -trustcacerts -keystore keystore1.p12 -alias cert1_alias -file exported_cert.cer

And that's basically it. The keytool will ask you for the keystore password and confirmation if you are sure what you are doing.

From then on your Java program that uses given truststore will trust all certificates that you imported.

BTW, if your application doesn't explicitly use it's own trust store, you can add your trusted certificate to the default Java CA store in a similar way.

keytool -import -trustcacerts -keystore $JAVA_HOME/jre/lib/security/cacerts -storepass changeit -alias cert1_alias -file exported_cert.cer

But be careful. This will make the certificate trusted to all application using given Java runtime environment, and this may not be what you want to do.

Keywords: java ssl certificate security