Categories
Technology

Import SSL certificate into Java KeyStore

How-To steps to import SSL certificates into Java trust KeyStore inside a Docker container

This post explores the steps that exports and imports the SSL certificate into Java KeyStore

In Java applications, to consume services or to communicate to servers over HTTPS protocol, Java needs to be “informed & introduced” of the application which sits on the other side. SSL public certificate facilitates this and other concerns like encryption and authentication.

Java has an in-built “container” for storing these certificates and public key certificates called Java KeyStore.

We can work with this KeyStore through Java’s Keytool utility. Refer this page for complete documentation

In the below sample, let’s export the SSL certificate of Google.com and import into Java’s KeyStore. Often we will come across this use case when we want to integrate and use Google’s services like reCaptcha or numerous other APIs.

Time needed: 5 minutes.

Export & Import the SSL Certificate to Java KeyStore

  1. Export the SSL certificate by OpenSSL tool

    echo | openssl s_client -servername NAME -connect www.google.com:443 |\
    sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > gcert.crt

  2. Copy the exported certificate to Docker file system

    docker cp SRC_PATH CONTAINER:DEST_PATH
    or
    Copy the file to the shared volume if a Container Volume Mount is available.

  3. Import the certificate into Java KeyStore using keytool utility

    keytool -import -alias www.google.com -file CERT_FILE_PATH -keystore $JAVA_HOME/jre/lib/security/cacerts -storepass changeit -trustcacerts

    note: “changeit” is the default password of the Java KeyStore.

Certificates should also be imported to the Web or Application servers like Oracle Weblogic, if it’s used.

keytool -import -alias www.google.com -file CERT_FILE_PATH -keystore $WEBLOGIC_HOME/server/lib/cacerts -storepass changeit -trustcacerts

In containers, you will need root user access to import the SSL certificate into the Java KeyStore using the Keytool utility tool, since normal user access will not be sufficient. Check out this post on how to login to the Docker container as Root user.

Checkout the following commands, can be handy..

How to list all the certificates in the Java KeyStore?

keytool -list -v -keystore $JAVA_HOME/jre/lib/security/cacerts

How to print or validate a certificate in the Java KeyStore?

keytool -printcert -v -file www_google_com.crt

The above procedure will be also used to fix the common networking exception javax.net.ssl.SSLHandshakeException

Remember certificates do have an expiry date and even though you import a certificate, once the certificates are expired, one will face the SSLHandshakeException. Now you know what to do 😉

Happy coding..!!!

Leave a Reply

Your email address will not be published. Required fields are marked *