简体   繁体   中英

SSLHandshakeException: PKIX path building failed SunCertPathBuilderException: unable to find valid certification path to requested target

I have copied PEM files cert.crt.pem and cert.key.pem in a file path and on executing the following code for the REST service with the details url, message type, pem file and password, it errors out with "SSLHandshakeException".

Exception:

Connecteion Ex: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

Code:

class RestWebServicePEM {

    public static void main(String[] args) {
        String url = "<authenticate_url>";
        String msgType = "application/json";
        String method = "POST";
        String pass = "<password>";
        File certKeyFile = new File("cert.crt.pem");
        File privateKeyFile = new File("cert.key.pem");

       
         HttpsURLConnection con = getSslConnection(url, msgType, method, privateKeyFile, certKeyFile, pass);
         int responseCode = con.getResponseCode();
       
    }

    private HttpsURLConnection getSslConnection(String inUrl, String inMsgType, String inMethod,
                                                File privateKeyPem, File certificatePem, String password) {
        HttpsURLConnection con = null;
        SocketFactory sslSocketFactory = createSSLSocketFactory(privateKeyPem, certificatePem, password);
        HttpsURLConnection.setDefaultSSLSocketFactory(sslSocketFactory);
        try {
            URL url = new URL(inUrl);
            con = (HttpsURLConnection) url.openConnection();
            con.setSSLSocketFactory(sslSocketFactory);
            if (inMethod == "POST") {
                con.setRequestMethod(inMethod);
                con.setDoOutput(true);
            }

            con.setInstanceFollowRedirects(true);
            con.setConnectTimeout(30000);
            con.setReadTimeout(30000);

            con.setRequestProperty("Content-Type", inMsgType);

            con.connect();
        } catch (Exception e) {
            if (con)
                con.disconnect();
            con = null;
        }
        return con;
    }

    private SSLSocketFactory createSSLSocketFactory(File privateKeyPem, File certificatePem, String password) throws Exception {
        SSLContext context = SSLContext.getInstance("TLS");
        KeyStore keystore = createKeyStore(privateKeyPem, certificatePem, password);
        KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
        kmf.init(keystore, password.toCharArray());
        KeyManager[] km = kmf.getKeyManagers();
        context.init(km, null, null);
        return context.getSocketFactory();
    }

    private KeyStore createKeyStore(File privateKeyPem, File certificatePem, final String password)
            throws Exception, KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException {
        X509Certificate[] cert = createCertificates(certificatePem);
        KeyStore keystore = KeyStore.getInstance("JKS");
        keystore.load(null);

        PrivateKey key = createPrivateKey(privateKeyPem);
        keystore.setKeyEntry(privateKeyPem.getName(), key, password.toCharArray(), cert);
        return keystore;
    }

    private PrivateKey createPrivateKey(File privateKeyPem) throws Exception {
        BufferedReader r = new BufferedReader(new FileReader(privateKeyPem));
        String s = r.readLine();

        while (s != null) {
            if (s.contains("BEGIN PRIVATE KEY")) {
                break;
            }
            s = r.readLine();
        }

        StringBuilder b = new StringBuilder();
        s = "";
        while (s != null) {
            if (s.contains("END PRIVATE KEY")) {
                break;
            }
            b.append(s);
            s = r.readLine();
        }
        r.close();
        String hexString = b.toString();
        byte[] bytes = DatatypeConverter.parseBase64Binary(hexString);
        return generatePrivateKeyFromDER(bytes);
    }

    private X509Certificate[] createCertificates(File certificatePem) throws Exception {
        List<X509Certificate> result = new ArrayList<X509Certificate>();
        BufferedReader r = new BufferedReader(new FileReader(certificatePem));
        String s = r.readLine();
        while (s != null) {
            if (s.contains("BEGIN CERTIFICATE")) {
                break;
            }
            s = r.readLine();
        }

        StringBuilder b = new StringBuilder();
        while (s != null) {
            if (s.contains("END CERTIFICATE")) {
                String hexString = b.toString();
                final byte[] bytes = DatatypeConverter.parseBase64Binary(hexString);
                X509Certificate cert = generateCertificateFromDER(bytes);
                result.add(cert);
                addMessage("Certificate:"+cert);
                b = new StringBuilder();
            } else {
                if (!s.startsWith("----")) {
                    b.append(s);
                }
            }
            s = r.readLine();
        }
        r.close();

        return result.toArray(new X509Certificate[result.size()]);
    }

    private RSAPrivateKey generatePrivateKeyFromDER(byte[] keyBytes) throws InvalidKeySpecException, NoSuchAlgorithmException {
        PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory factory = KeyFactory.getInstance("RSA");
        return (RSAPrivateKey) factory.generatePrivate(spec);
    }

    private X509Certificate generateCertificateFromDER(byte[] certBytes) throws CertificateException {
        CertificateFactory factory = CertificateFactory.getInstance("X.509");
        return (X509Certificate) factory.generateCertificate(new ByteArrayInputStream(certBytes));
    }

}

You can fix this issue by adding certificate to the Java key store.

  1. Download the certificate.

  2. Go to the path <JAVA_HOME>...jre\lib\security.

  3. Keep the certificate here.

  4. Run the key tool command (Administrator mode) type password if it is asking for(changeit)

    keytool -keystore cacerts -importcert -alias "your alisa name" -file certificare name.cer

5.Now you can remove the SSL authentication code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

Related Question javax.mail.MessagingException: PKIX path building failed: SunCertPathBuilderException: unable to find valid certification path to requested target; PKIX path building failed: SunCertPathBuilderException: unable to find valid certification path to requested target PKIX building failed:sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target? CXF:PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target unable to find valid certification path to requested target PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException JDK8 -> JDK10: PKIX path building failed: SunCertPathBuilderException: unable to find valid certification path to requested target PKIX path building failed: SunCertPathBuilderException: unable to find valid certification path to requested Error in JavaMail : PKIX path building failed unable to find valid certification path to requested target
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM