Сбой построения пути PKIX в Java 7, но не в Java 8. Невозможно подключиться к моему HTTPS-серверу, несмотря на наличие сертификата Let's Encrypt, которому доверяют браузеры - PullRequest
0 голосов
/ 17 июня 2019

Я пишу настольное приложение, которое должно загрузить несколько файлов конфигурации с моего HTTPS-сервера, на котором работает действующий сертификат Let's Encrypt, которому доверяют Chrome и Firefox и Java 8. Я хочу, чтобы приложение было совместимым насколько возможно, поэтому я нацеливаюсь на Java 7 как минимум. В Java 7 приложение не может подключиться с ошибкой Caused by: 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

Я пробовал много решений, и это, кажется, ближе всего к моей проблеме:

«Ошибка построения пути PKIX», несмотря на действительный сертификат Verisign

К сожалению, с моим сервером все в порядке и https://www.ssllabs.com/ssltest/analyze.html?d=baldeonline.com показывает, что Java 7 ДОЛЖНА подключаться.

Как бы я использовал другое (или системное) хранилище сертификатов программно? Очевидно, что это не удобно для пользователя, если пользователь должен копаться в своей папке установки Java, поэтому я хотел бы внести какие-либо изменения в саму программу.

Функция, которая вызывает ошибку:

        try {
            URL obj = new URL(urlPointer);
            HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
            SSLContext sslContext = SSLContext.getInstance("TLSv1.2");//I have also tries TLSv1 but no difference 
            sslContext.init(null, null, new SecureRandom());
            con.setSSLSocketFactory(sslContext.getSocketFactory());
            con.setRequestMethod("GET");
            con.setRequestProperty("User-Agent", USER_AGENT);
            int responseCode = 0;
            try {
                responseCode = con.getResponseCode();
            } catch (IOException e) {
            }
            System.out.println("POST Response Code : " + responseCode);

            if (responseCode >= 400) {
                BufferedReader in = new BufferedReader(new InputStreamReader(
                        con.getErrorStream()));
                String inputLine;
                StringBuffer response = new StringBuffer();

                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();
                return response.toString();
            } else {
                BufferedReader in = new BufferedReader(new InputStreamReader(
                        con.getInputStream()));
                String inputLine;
                StringBuffer response = new StringBuffer();

                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();
                return response.toString();
            }

        } catch (IOException e) {
            e.printStackTrace();
            return "";
        } catch (NoSuchAlgorithmException e1) {
            e1.printStackTrace();
            return "";
        } catch (KeyManagementException e1) {
            e1.printStackTrace();
            return "";
        }

    }```

1 Ответ

0 голосов
/ 03 июля 2019

Поскольку я нигде не могу найти хорошего примера в Интернете, вот мое универсальное решение проблемы.Используйте набор корневых сертификатов, хранящихся ВНУТРИ файла jar, и разархивируйте их во время выполнения.Затем используйте сертификаты в диспетчере доверия, заменив старые Java.Закрепление сертификатов является приемлемым решением, если вы хотите подключиться только к одному серверу, однако это решение должно охватывать большую часть Интернета.Вам нужно откуда-то получить корневые сертификаты, я использовал хранилище Windows Trust для экспорта сертификатов в кодировке X.509 base64.

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;

public class CertificateHandler {
    public String thisJar = "";

    public CertificateHandler() {
        try {
            thisJar = getJarFile().toString();
            thisJar = thisJar.substring(6).replace("%20", " ");
        } catch (IOException e) {
            thisJar = "truststore.zip";
            e.printStackTrace();
        }
        //truststore.zip is used in place of the jar file during development and isn't needed once the jar is exported
    }

    public static TrustManagerFactory buildTrustManagerFactory() {
        try {
            TrustManagerFactory trustManager = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            try {
                KeyStore ks;
                ks = KeyStore.getInstance(KeyStore.getDefaultType());
                ks.load(null);
                File dir = new File(Launcher.launcherSafeDirectory + "truststore");
                File[] directoryListing = dir.listFiles();
                if (directoryListing != null) {
                    for (File child : directoryListing) {
                        try {   
                            InputStream is = new FileInputStream(child);
                            System.out.println("Trusting Certificate: "+child.getName().substring(0, child.getName().length() - 4));
                            CertificateFactory cf = CertificateFactory.getInstance("X.509");
                            X509Certificate caCert = (X509Certificate)cf.generateCertificate(is);
                            ks.setCertificateEntry(child.getName().substring(0, child.getName().length() - 4), caCert);
                        } catch (FileNotFoundException e2) {
                            e2.printStackTrace();
                        }
                    }
                }
                trustManager.init(ks);
            } catch (KeyStoreException | CertificateException | IOException | NoSuchAlgorithmException e1) {
                e1.printStackTrace();
            }

            return trustManager;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static TrustManager[] getTrustManagers() {
        TrustManagerFactory trustManager = buildTrustManagerFactory();
        return trustManager.getTrustManagers();
    }

    public void loadCertificates() {
        try {
            UnzipLib.unzipFolder(thisJar, "truststore", Launcher.launcherSafeDirectory + "truststore");
            System.out.println("Extracted truststore to "+ Launcher.launcherSafeDirectory);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    private File getJarFile() throws FileNotFoundException {
        String path = Launcher.class.getResource(Launcher.class.getSimpleName() + ".class").getFile();
        if(path.startsWith("/")) {
            throw new FileNotFoundException("This is not a jar file: \n" + path);
        }
        path = ClassLoader.getSystemClassLoader().getResource(path).getFile();
        return new File(path.substring(0, path.lastIndexOf('!')));
    }
}

Приведенный выше код обрабатывает создание массива TrustManager [], который можно использоватьв соединениях HTTPS следующим образом:

private static final String USER_AGENT = "Mozilla/5.0";

static String sendPOST(String POST_URL, String POST_PARAMS, TrustManager[] trustManagers) {
    try {
        URL obj = new URL(POST_URL);
        HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
        SSLContext sslContext = SSLContext.getInstance("TLSv1.2"); 
        sslContext.init(null, trustManagers, new SecureRandom());
        con.setSSLSocketFactory(sslContext.getSocketFactory());
        con.setRequestMethod("POST");
        con.setRequestProperty("Content-Type", "application/json; utf-8");
        con.setRequestProperty("Accept", "application/json");
        con.setRequestProperty("User-Agent", USER_AGENT);

        // For POST only - START
        con.setDoOutput(true);
        OutputStream os = con.getOutputStream();
        os.write(POST_PARAMS.getBytes());
        os.flush();
        os.close();
        // For POST only - END
        int responseCode = 0;

        try {
            //sendPOST("http://localhost", postParams);
            responseCode = con.getResponseCode();
        } catch (IOException e) {
        }
        System.out.println("POST Response Code : " + responseCode);

        if (responseCode >= 400) {
            BufferedReader in = new BufferedReader(new InputStreamReader(
                    con.getErrorStream()));
            String inputLine;
            StringBuffer response = new StringBuffer();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
            return response.toString();
        } else {
            BufferedReader in = new BufferedReader(new InputStreamReader(
                    con.getInputStream()));
            String inputLine;
            StringBuffer response = new StringBuffer();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
            return response.toString();
        }

    } catch (KeyManagementException | NoSuchAlgorithmException | IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    return "";
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...