Java uses the keystore file named cacerts. It should already contain all trusted root CA certificates that are used to sign intermediate and leaf certificates. Leaf certificates are end user certificates that are used to secure websites with HTTPS. However, sometimes a root CA certificate might be missing from the Java keystore or a website might be using a self-signed certificate which will result in the following exception when you try to access the website from Java code:
javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested targetFor me it happened with a certificate issued by COMODO. In this case the easiest solution is to add the website certificate to the Java keystore. Shortly, it requires exporting the certificate from the website, importing it into the keystore and restarting your Java application.
Please bear in mind that importing a self-signed certificate this way will merely hide the security issue and not solve it. So you should always use reliable trusted certificates on Production, for example, there are free ones issued by Let's Encrypt Certificate Authority.
Export website certificate
The following command will save the website certificate to a local file provided you set $HOST and $PORT variables accordingly:
echo -n | openssl s_client -connect $HOST:$PORT | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > $HOST.cert
Import certificate to Java keystore
The following command will import the certificate $FILE with the alias $NAME in the cacerts Java keystore where "changeit" is the default password.
keytool -keystore cacerts -importcert -alias $NAME -file $FILE -storepass changeit
Combined script
Finally let's combine it into a nice script to speed up the process. We'll create a script named import_certificate.sh.
#!/bin/sh HOST=$1 PORT=$2 echo -n | openssl s_client -connect $HOST:$PORT | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > $HOST.cert name=`echo $HOST | tr '.' '_'` echo keytool -keystore cacerts -importcert -alias $name -file $HOST.cert -storepass changeit
Now in order to fix the issue with untrusted certificate, just run it the following way:
import_certificate.sh www.website.com 443
Comments
Post a Comment