Friday, May 25, 2012

Avoiding the "javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed" error

Hey folks,

today I'm gonna share one solution for a problem related to https hand-shake.

The SSLHandshakeException is thrown by java when the host you are trying to contact doesn't have a valid SSL certificate for that hostname.
For example, when I wanted to connect to the site which certificate details look like  "This CA Root certificate is not trusted because it is not in the Trusted Root Certification Authorities store.

So when we are making a request to that site using java URLConnection it gives us an exception look like "javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed" . Then I did research for this problem and found a solution as follows:



package com.blogspot.vmustafayev4en.ca;

import javax.net.ssl.*;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class TestHttps {
    public static void main(String args[]) throws Exception {

        // Create a trust manager that does not validate certificate chains
        TrustManager[] trustAllCerts = new TrustManager[]{
                new X509TrustManager() {
                    public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                        return null;
                    }

                    public void checkClientTrusted(
                            java.security.cert.X509Certificate[] certs, String authType) {
                    }

                    public void checkServerTrusted(
                            java.security.cert.X509Certificate[] certs, String authType) {
                    }
                }
        };

        // Install the all-trusting trust manager
        try {
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        } catch (Exception e) {
            System.out.println("Error" + e);
        }

        // Now you can access URL(https) without having the certificate in the truststore
        try {

            HostnameVerifier hv = new HostnameVerifier() {
                public boolean verify(String urlHostName, SSLSession session) {
                    System.out.println("Warning: URL Host: " + urlHostName + " vs. "
                            + session.getPeerHost());
                    return true;
                }
            };

            String datam = "param=myparam";
            URL url = new URL("https://myurlgoeshere/blabla.aspx");
            URLConnection conn = url.openConnection();
            HttpsURLConnection urlConn = (HttpsURLConnection) conn;
            urlConn.setHostnameVerifier(hv);
            conn.setDoOutput(true);
            OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
            wr.write(datam);
            wr.flush();

            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));

            StringBuilder sb = new StringBuilder();
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                sb.append(inputLine);
            }
            in.close();
            String res = sb.toString();
            System.out.println(res);

        } catch (MalformedURLException e) {
            System.out.println("Error in SLL Connetion" + e);
        }


    }
}
That is all what you need to prevent that exception. We use VPN connection so don't need Certificate :)

If you are going to master Java and looking for a cheap course I'd strongly recommend you check out Java Programming Masterclass for Software Developers which is already taken by 300k+ students and has a great rating.

Hope it was useful. Thanks for reading!

9 comments:

  1. Great work. However I am trying to understand. Thanks a lot.

    ReplyDelete
  2. Awesome Blog. Resolved one of our issues like a smooth piece of cheese cake

    ReplyDelete
  3. Welcome :) Please share with friends as well

    ReplyDelete
  4. Vasif Mustafayev'S Blog: Avoiding The "Javax.Net.Ssl.Sslhandshakeexception: Sun.Security.Validator.Validatorexception: Pkix Path Building Failed" Error >>>>> Download Now

    >>>>> Download Full

    Vasif Mustafayev'S Blog: Avoiding The "Javax.Net.Ssl.Sslhandshakeexception: Sun.Security.Validator.Validatorexception: Pkix Path Building Failed" Error >>>>> Download LINK

    >>>>> Download Now

    Vasif Mustafayev'S Blog: Avoiding The "Javax.Net.Ssl.Sslhandshakeexception: Sun.Security.Validator.Validatorexception: Pkix Path Building Failed" Error >>>>> Download Full

    >>>>> Download LINK 0B

    ReplyDelete
  5. Vasif Mustafayev'S Blog: Avoiding The "Javax.Net.Ssl.Sslhandshakeexception: Sun.Security.Validator.Validatorexception: Pkix Path Building Failed" Error >>>>> Download Now

    >>>>> Download Full

    Vasif Mustafayev'S Blog: Avoiding The "Javax.Net.Ssl.Sslhandshakeexception: Sun.Security.Validator.Validatorexception: Pkix Path Building Failed" Error >>>>> Download LINK

    >>>>> Download Now

    Vasif Mustafayev'S Blog: Avoiding The "Javax.Net.Ssl.Sslhandshakeexception: Sun.Security.Validator.Validatorexception: Pkix Path Building Failed" Error >>>>> Download Full

    >>>>> Download LINK iL

    ReplyDelete