Search code examples
javahttpsjsoupkeystoretruststore

Jsoup connection to https(keystore)


I have a problem with connection(login) to https://jizdenky.regiojet.cz/Login?0.

Code:

//add certificate to trustStore
System.setProperty("javax.net.ssl.trustStore", "keystore/regionjet.jks");
Connection connection = Jsoup.connect("https://jizdenky.regiojet.cz/Login?0");
Connection.Response response = connection.data("passwordAccountCode", username).data("password", password).method(Connection.Method.POST).execute();

and i still get exception with certification path

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

Anyone could help me or telling me where is problem?


Solution

  • You could do two things. I am just reffering here to also answered questions.

    Generally allow all certificates

    Read this answer: https://stackoverflow.com/a/2793153/3977134

    And the corresponding code is:

    TrustManager[] trustAllCertificates = new TrustManager[] {
        new X509TrustManager() {
            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null; // Not relevant.
            }
            @Override
            public void checkClientTrusted(X509Certificate[] certs, String authType) {
                // Do nothing. Just allow them all.
            }
            @Override
            public void checkServerTrusted(X509Certificate[] certs, String authType) {
                // Do nothing. Just allow them all.
            }
        }
    };
    
    HostnameVerifier trustAllHostnames = new HostnameVerifier() {
        @Override
        public boolean verify(String hostname, SSLSession session) {
            return true; // Just allow them all.
        }
    };
    
    try {
        System.setProperty("jsse.enableSNIExtension", "false");
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCertificates, new SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        HttpsURLConnection.setDefaultHostnameVerifier(trustAllHostnames);
    }
    catch (GeneralSecurityException e) {
        throw new ExceptionInInitializerError(e);
    }
    

    Add the certificate to the store of your JRE

    This method requires you to download the CRT file from e.g. your browser. After that you should include it into your JRE using the keytool command which is part of the JRE.

    A complete answer is here: https://stackoverflow.com/a/7745706/3977134