Skip to main content

How to avoid SSLHandshakeException while connecting to HTTPS urls

Have you got a javax.net.ssl.SSLHandshakeException while trying to connect to a URL which is SSL encrypted? You want to connect to a web page or a SOAP Web Service from your Java application but it is throwing the below exception:

Exception in thread "main" 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

The error says the connection could not be established due to a certificate validation error. You might be wondering why some urls are working while some not. To understand this you need to know what is SSL and how SSL works.

What is Secure Socket Layer?

SSL stands for Secure Socket Layer which is a protocol in which the data transfer between a Web Client(e.g. web browser) and a Web Server takes place in an encrypted format. Content encrypted by the server is decrypted by the client using a public-private key pair.

Key pairs contains a public key and a private key, content encrypted with one key can be decrypted with the other. All modern browsers includes a set of well known certificates issued by certificate authorities(CA), which makes the encryption-decryption possible for HTTPS sites.

Why Java throwing javax.net.ssl.SSLHandshakeException for some SSL sites?

As in browser, JRE also contains a trustsore where all trusted CA certificates are stored. This truststore is stored in a file named cacerts located at <JRE_HOME>/lib/security/. You can connect to all HTTPS sites which are having certificates trusted by Java truststore but a SSLHandshakeException is thrown for sites with untrusted certificates(including self signed certificates).

How to avoid SSLHandshakeException?

There are many ways to overcome SSLHandshakeException, some are given below:

  1. Adding certificate to Java trust store manually
  2. Adding certificate to Java trust store programmatically
  3. Use custom trust store
  4. Turn off certificate validation

Safest option is to add the certificate to Java trust store manually to avoid any security issues.

How to add SSL certificate to the Java Truststore?

It is a two step process, first download the certificate, then add the certificate to the truststore.

1. Downloading the certificate

First, open the url in your browser(steps may vary depends on the browser), then click on the lock icon on the navigation bar, then click on Certificate Information. Now go to Details tab, there you will see a Copy to File button. Clicking on this will give you a certificate export wizard where you need to select certificate format as DER encoded binary X.509. Give a file name say mycertificate.cer and save the file.

2. Adding certificate to the Java truststore

This is a simple step, go to <JRE_HOME>/bin and execute the below command:

keytool -import -alias alias -keystore ../lib/security/cacerts 
      -file mycertificate.cer
Enter the default keystore password 'changeit'(changeme on Mac) for the prompt 'Enter keystore password:'.

Then enter 'yes' for the prompt 'Trust this certificate? [no]:' and press enter key.

If everything goes well, you will get a message 'Certificate was added to keystore' which confirms your certificate is added to the Java truststore successfylly!

Connecting to a HTTPS site with URLConnection

Below program will now work without any SSL handshake exception:

 URL url = new URL("https://secure.skunkworks.net.au");
 URLConnection con = url.openConnection();
 con.connect();
  
 InputStream in = con.getInputStream();
 InputStreamReader inputstreamreader = new InputStreamReader(in);
 BufferedReader bufferedreader = new BufferedReader(inputstreamreader);

 String string = null;
 while ((string = bufferedreader.readLine()) != null) {
  System.out.println(string);
 } 

That's it, now you learnt how to connect to a SSL secured url from a Java application!

Those who want to connect to a mail server over SSL using Java Mail API, use the below property to authenticate over SSL:

 props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");

Comments

Popular posts from this blog

HDFC Bank introduces Missed Call Service to know Account Balance

Missed call is a powerful business tool in developing countries like India where customers give a miss call to specific phone numbers for getting account details, providing feedback, voting etc. On receiving a missed call from a registered phone number, the underlying app performs a phone number lookup and sends the data to the caller via text message(SMS) or records the call details for future processing.HDFC Bank recently introduced missed call service for its retail customers which allows to retrieve bank account details, mini statement etc. by simply giving a miss call to their toll free numbers.Following services are now available: 1800 270 3333 - Account Balance 1800 270 3355 - Mini Statement 1800 270 3366 - Request for new Cheque Book 1800 270 3377 - Request for Bank account statement Also you can download HDFC Mobile Banking Application by giving a missed call to : 1800 270 3344. Other banks providing missed call serviceAxis bank(known as Axis Dial) - 09225892258Bank of India…

Induction Cooker Showing an Error Code? Induction Cooker Error Codes Explained

Are you searching for Induction Cook-top error codes? Here you can find the error codes of all popular induction cooktops and how to troubleshoot it.

These are for your reference only, do not try to open your cooktop without proper safety measures, we advise you to call the service person if any servicing is needed.

If you want to know how Induction Cook-top works, read our previous article titled What is Induction Cooker? How Induction Cooker Works?.

Whirlpool Induction Cooker Error CodesError CodeErrorSolutionF0An internal error was detected.Disconnect power. Wait 5 seconds before reconnecting power. If the symbol appears again, call for service.F2The surface cooking area is too hot and has turned off.Remove the pans from the surface cooking area. "F2" will disappear when the surface cooking area has cooled. If you turn the surface cooking area back on and "F2" reappears, the cooktop is still too hot. Turn off the surface cooking area and allow it to cool.F4The po…

LICHFL - Generating Home Loan Statements Online

Generating an online statement from LIC Housing Finance Ltd is very easy, simply follow the below steps to create an online account with LICHFL and generate statements online! You may use the online generated statement as a proof for principal paid for a housing loan(under section 80C) and interest paid(under section 24) while filing income tax returns.Want to know how to save maximum income tax? Read our most read article how to save maximum income tax(opens in new tab).Before reading further, make sure you have the following information with you: Your Loan Account NumberSanctioned AmountStep 1 - Open LICHFL websiteVisit LICHFL website and click on the 'New Customers? Click Here' link(refer the below screenshot). Step 2 - Enter your loan account detailsFill in the following details: New Loan NumberSanctioned AmountDate of BirthSecurity Codeand click on the Submit button. Step 3 - Enter your personal detailsEnter your email address, a username and password and click on submi…