Add Root Certificate to Java Keystore

2019-02-22 - Shows how to add a root certificate to the Java keystore

1. SSL Certificates

It has certainly happened that you wanted to use your Java-based application to connect to an https resource that 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 those settings and proclaim that the site with the given (self-signed, invalid, …) certificate is secure.

This can be done quite easily by adding that certificate to the Java certificate truststore.

All you need is the 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 the 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 that you are sure what you are doing.

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

BTW, if your application doesn't explicitly use its own truststore, 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 by all applications using the given Java runtime environment, and this may not be what you want.

Keywords: java ssl certificate security