SSLHandshakeException: When trying trying to access a HTTPS URL

I was trying to access a HTTPS URL using java.net.HttpURLConnection and got following error.

Error
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 target
Most of the time, this exception occurs when you are using selfsigned certificate.

Reason:  The host that you are trying to connect has an self signed certificate, and that certificate is not in your truststore.

Description:
Actually I am using the tomcat server and I have enabled HTTPS connector. I have created a selfsigned certificate for the tomcat.

I have a standalone Java program which connects to the server and downloads file over HTTPS. But when I try to connect to the server, it threw SSLHandshakeException.

Solution:  Solution to resolve this exception is to import the selfsigned certificate into the system truststore.
Below steps explains how to do it.

Step-1: Export the certificate.

Export your self signed certificate using keytool utility provided with JDK.open the command prompt and change current directory to JAVA_HOME/bin. Now run following command.

keytool -export -alias tomcat -storepass changeit  -file tomcat.cer

It will create a tomcat.cer file in the current directory.

Note: You may need to modify -alias and -storepass options if required. Default keystore  password is ‘changeit’.

Step-2: Import the certificate into truststore.

keytool -import -alias tomcat -file tomcat.cer -keystore <path to JAVA_HOME>\jre\lib\security\cacerts
or
keytool -import -alias tomcat -file tomcat.cer -keystore ..\jre\lib\security\cacerts

It will ask you to enter keystore password. Default password is ‘changeit’.  when it ask, ‘Trust this certificate?’, type yes and press enter.

Step-3: Verify that the certificate is added successfully

keytool -list -keystore C:\j2sdk1.4.2_16\jre\lib\security\cacerts

It will list all the certificate. verify that the certificate you just added is present in list.

That’s it! now run your program again.

Advertisements
Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: