Question

I'm building a server that has to call two webservices. Webservices have the same CA certificate (PKCS12).

the first one receives request by GET, the other one by SOAP call.

follow a part of code that creates connection for GET request

            InputStream inputStream = null;

            // is https protocol?
            if (url.getProtocol().toLowerCase().equals("https")) {

                trustAllHosts();
                // create connection
                HttpsURLConnection httpsUrlConnection = null;
                if(proxy != null){
                    httpsUrlConnection = (HttpsURLConnection) url.openConnection(proxy);
                } else {
                    httpsUrlConnection = (HttpsURLConnection) url.openConnection();
                }
                // set the check to: do not verify
                httpsUrlConnection.setHostnameVerifier(new HostnameVerifier() {
                    @Override
                    public boolean verify(String hostname, SSLSession session) {
                        return true;
                    }
                });

                setHeaders(httpsUrlConnection, headers);    

                //set del certificato

                log.debug("set certificate for get...");
                File cerp12 = new File(Utils.getWebAppLocalPath(),"WEB-INF"+String.valueOf(File.separatorChar)+PropConfig.getProperty("cer.p12"));
                ((HttpsURLConnection) httpsUrlConnection).setSSLSocketFactory(security(cerp12,PropConfig.getProperty("cer.pwd"))); 
                httpsUrlConnection.connect();

                inputStream = httpsUrlConnection.getInputStream();

            } else {
                HttpURLConnection httpUrlConnection = null;
                if(proxy != null){
                    httpUrlConnection = (HttpURLConnection) url.openConnection(proxy);
                } else {
                    httpUrlConnection = (HttpURLConnection) url.openConnection();
                }

                setHeaders(httpUrlConnection, headers);    

                inputStream = httpUrlConnection.getInputStream();
            }

            in = new BufferedReader(new InputStreamReader(inputStream));

            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                result.append(inputLine);
            }

and this part is for SOAP request

            InputStream inputStream = null;

            // is https protocol?
            if (url.getProtocol().toLowerCase().equals("https")) {

                trustAllHosts();
                // create connection
                HttpsURLConnection httpsUrlConnection = null;
                if(proxy != null){
                    httpsUrlConnection = (HttpsURLConnection) url.openConnection(proxy);
                } else {
                    httpsUrlConnection = (HttpsURLConnection) url.openConnection();
                }
                // set the check to: do not verify
                httpsUrlConnection.setHostnameVerifier(new HostnameVerifier() {
                    @Override
                    public boolean verify(String hostname, SSLSession session) {
                        return true;
                    }
                });

                setHeaders(httpsUrlConnection, headers);    

                //set del certificato

                log.debug("set certificate for get...");
                File cerp12 = new File(Utils.getWebAppLocalPath(),"WEB-INF"+String.valueOf(File.separatorChar)+PropConfig.getProperty("cer.p12"));
                ((HttpsURLConnection) httpsUrlConnection).setSSLSocketFactory(security(cerp12,PropConfig.getProperty("cer.pwd"))); 
                httpsUrlConnection.connect();

                inputStream = httpsUrlConnection.getInputStream();

            } else {
                HttpURLConnection httpUrlConnection = null;
                if(proxy != null){
                    httpUrlConnection = (HttpURLConnection) url.openConnection(proxy);
                } else {
                    httpUrlConnection = (HttpURLConnection) url.openConnection();
                }

                setHeaders(httpUrlConnection, headers);    

                inputStream = httpUrlConnection.getInputStream();
            }

            in = new BufferedReader(new InputStreamReader(inputStream));

            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                result.append(inputLine);
            }

the code is almost the same

with GET request I have no problem, but with SOAP request httpsUrlConnection.connect(); throws PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

Was it helpful?

Solution

Here is howto create ssl context for HTTPS connection.

        SSLSocketFactory socketFactory = createSSLContext().getSocketFactory();

        HttpsURLConnection connection = (HttpsURLConnection) (url).openConnection();
        connection.setSSLSocketFactory(socketFactory);

And method to create SSL context. Note, it load root server certificate from .pem file (x509 format) and client certificate from .p12 (pkcs12 format). If server don't required client certificate, pass null for key managers. If server sertificate issued by authority, which already in $JRE_HOME/lib/security/cacerts, pass null as trust managers.

And one more note: in .pem file you should store root certificate in PKIX path of server certificate. For example, github.com That site has PKIX path CN = github.com -> CN = DigiCert High Assurance EV CA-1 -> CN = DigiCert High Assurance EV Root CA -> CN = GTE CyberTrust Global Root. So you store GTE CyberTrust Global Root

private final SSLContext createSSLContext()
            throws NoSuchAlgorithmException, KeyStoreException,
            CertificateException, IOException,
            UnrecoverableKeyException, KeyManagementException {


        KeyStore keyStore = KeyStore.getInstance("PKCS12");

        FileInputStream fis = null;
        try {
            fis = new FileInputStream(new File(Config.getString(Config.KEYSTORE_PATH)));
        } catch (Exception ex) {
            throw new IOException("not found keystore file: " Config.getString(Config.KEYSTORE_PATH), ex);
        }
        try{
            keyStore.load(fis, Config.getString(Config.KEYSTORE_PASSWORD).toCharArray());
        }finally {
            IOUtils.closeQuietly(fis);
        }
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        FileInputStream in = new FileInputStream(Config.getString(Config.HTTPS_SERVER_CERT));
        KeyStore trustStore = KeyStore.getInstance("JKS");
        trustStore.load(null);
        try {
            X509Certificate cacert = (X509Certificate) cf.generateCertificate(in);
            trustStore.setCertificateEntry("alias", cacert);
        } finally {
            IOUtils.closeQuietly(in);
        }

        TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
        tmf.init(trustStore);

        KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
        kmf.init(keyStore, Config.getString(Config.KEYSTORE_PASSWORD).toCharArray());

        SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), new SecureRandom());
        return sslContext;
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top