简体   繁体   English

SSLHandshakeException:PKIX 路径构建失败 SunCertPathBuilderException:无法找到请求目标的有效证书路径

[英]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".我已将 PEM 文件 cert.crt.pem 和 cert.key.pem 复制到文件路径中,并为 REST 服务执行以下代码,其中包含详细信息 url、消息类型、pem 文件和密码,它会出现“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连接示例:javax.net.ssl.SSLHandshakeException:sun.security.validator.ValidatorException:PKIX 路径构建失败:sun.security.provider.certpath.SunCertPathBuilderException:无法找到请求目标的有效证书路径

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.您可以通过将证书添加到 Java 密钥库来解决此问题。

  1. Download the certificate.下载证书。

  2. Go to the path <JAVA_HOME>...jre\lib\security. Go 到路径 <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)运行关键工具命令(管理员模式)如果要求输入密码(changeit)

    keytool -keystore cacerts -importcert -alias "your alisa name" -file certificare name.cer keytool -keystore cacerts -importcert -alias "你的别名" -file certificare name.cer

5.Now you can remove the SSL authentication code. 5.现在可以去掉SSL认证码了。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 javax.mail.MessagingException:PKIX 路径构建失败:SunCertPathBuilderException:无法找到请求目标的有效证书路径; - javax.mail.MessagingException: PKIX path building failed: SunCertPathBuilderException: unable to find valid certification path to requested target; PKIX 路径构建失败:SunCertPathBuilderException:无法找到到请求目标的有效认证路径 - PKIX path building failed: SunCertPathBuilderException: unable to find valid certification path to requested target PKIX 构建失败:sun.security.provider.certpath.SunCertPathBuilderException:无法找到请求目标的有效证书路径 - PKIX building failed:sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target PKIX路径构建失败:sun.security.provider.certpath.SunCertPathBuilderException:无法找到到请求目标的有效认证路径? - PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target? CXF:PKIX 路径构建失败:sun.security.provider.certpath.SunCertPathBuilderException:无法找到请求目标的有效证书路径 - CXF:PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target PKIX路径构建失败:sun.security.provider.certpath.SunCertPathBuilderException:无法找到到请求目标的有效认证路径 - PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target 无法找到到请求的目标PKIX路径构建的有效证书路径失败:sun.security.provider.certpath.SunCertPathBuilderException - unable to find valid certification path to requested target PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException JDK8-&gt; JDK10:PKIX路径构建失败:SunCertPathBuilderException:无法找到到请求目标的有效证书路径 - JDK8 -> JDK10: PKIX path building failed: SunCertPathBuilderException: unable to find valid certification path to requested target PKIX 路径构建失败:SunCertPathBuilderException:无法找到请求的有效证书路径 - PKIX path building failed: SunCertPathBuilderException: unable to find valid certification path to requested JavaMail中的错误:PKIX路径构建失败,无法找到所请求目标的有效证书路径 - Error in JavaMail : PKIX path building failed unable to find valid certification path to requested target
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM