Java PKIX路径生成失败:找不到请求目标的有效证书路径

Java PKIX路径生成失败:找不到请求目标的有效证书路径,java,web-services,certificate,ssl-certificate,Java,Web Services,Certificate,Ssl Certificate,我正在调用某个HTTPS web服务,该服务由以下客户端提供: import java.io.ByteArrayOutputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintStream; import java.net.HttpURLConnection;

我正在调用某个HTTPS web服务,该服务由以下客户端提供:

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;

/**
 * Handles http and https connections. It sends XML request over http (or https)
 * to SOAP web service and receive the XML reply.
 * 
 * @author mhewedy
 * @date 30.10.2010
 */
public class HttpWSXmlClient
{
    private final String ws_url;
    private byte[] requestData;

    public HttpWSXmlClient(String wsUrl)
    {
        this.ws_url = wsUrl;
    }

    public void readRequest(String xmlRequestFilePath)
    {
        try
        {
            InputStream istream = new FileInputStream(xmlRequestFilePath);
            byte[] data = stream2Bytes(istream);
            istream.close();
            this.requestData = data;
        } catch (Exception e)
        {
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * 
     * @param ps
     *            PrintStream object to send the debugging info to.
     * @return
     * @throws IOException
     */
    public byte[] sendAndRecieve(PrintStream ps) throws IOException
    {
        if (requestData == null)
            throw new RuntimeException(
                    "the request data didn't initialized yet.");
        if (ps != null)
            ps.println("Request:\n" + new String(requestData));
        URL url = new URL(ws_url);
        HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
        // or HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setRequestProperty("content-type", "text/xml");
        connection.connect();
        OutputStream os = connection.getOutputStream();
        os.write(requestData);
        InputStream is = connection.getInputStream();
        byte[] rply = stream2Bytes(is);
        if (ps != null)
            ps.println("Response:\n" + new String(rply));
        os.close();
        is.close();
        connection.disconnect();
        return rply;
    }

    public byte[] sendAndRecieve() throws IOException
    {
        return sendAndRecieve(null);
    }

    private byte[] stream2Bytes(InputStream istream) throws IOException
    {
        ByteArrayOutputStream outstream = new ByteArrayOutputStream();
        int c;
        while ((c = istream.read()) != -1)
        {
            if (c != 0x0A && c != 0x0D) // prevent new line character from being
            // written
            {
                if (c == 0x09)
                    c = 0x20; // prevent tab character from being written,
                // instead write single space char
                outstream.write(c);
            }
        }
        byte[] ret = outstream.toByteArray();
        outstream.close();
        return ret;
    }

}
测试:

我得到了以下输出:

Exception in thread "Main Thread" 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
    at com.sun.net.ssl.internal.ssl.Alerts.getSSLException(Alerts.java:174)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1591)
    at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Handshaker.java:187)
    at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Handshaker.java:181)
    at com.sun.net.ssl.internal.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1035)
    at com.sun.net.ssl.internal.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:124)
    at com.sun.net.ssl.internal.ssl.Handshaker.processLoop(Handshaker.java:516)
    at com.sun.net.ssl.internal.ssl.Handshaker.process_record(Handshaker.java:454)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:884)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1096)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1123)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1107)
    at sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:415)
    at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:166)
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.connect(HttpsURLConnectionImpl.java:133)
    at com.se.swstest.HttpWSXmlClient.sendAndRecieve(HttpWSXmlClient.java:63)
    at com.se.swstest.Test.main(Test.java:11)
Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:285)
    at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:191)
    at sun.security.validator.Validator.validate(Validator.java:218)
    at com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:126)
    at com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:209)
    at com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:249)
    at com.sun.net.ssl.internal.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1014)
    ... 12 more
Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:174)
    at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:238)
    at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:280)
    ... 18 more
我需要任何证书放在jdk/jre/lib/security吗??? 另外,我有一个xxx_IE.crt和xxx_FX.crt(分别用于Firefox和IE,它们不适用于上述Java客户端,所以我需要Java客户端的特定证书吗


谢谢。

您需要设置证书才能访问此url。请使用以下代码设置密钥库:

System.setProperty("javax.net.ssl.trustStore","clientTrustStore.key");

System.setProperty("javax.net.ssl.trustStorePassword","qwerty");

我曾多次遇到这种情况,这是因为证书链不完整。如果您使用的是标准java信任存储,它可能没有完成证书链所需的证书,而证书链是验证您连接的SSL站点的证书所需的


我在使用一些DigiCert证书时遇到了这个问题,不得不自己手动添加中间证书。

对于我来说,我在调用webservice调用时遇到了这个错误,请确保站点具有有效的ssl,即检查url一侧的徽标,否则需要将证书添加到mach中的受信任密钥存储中在Mac OS上,我必须使用系统密钥链访问工具打开服务器的自签名证书,导入它,多宝单击它,然后选择“始终信任”(即使我在导入器中设置了相同的设置)。
在此之前,我当然运行了java key Take with-importcert将同一文件导入到cacert存储。

我也遇到了这种问题。我使用tomcat服务器,然后我在tomcat中放置了已认可的文件夹,然后它开始工作。我还用1.7替换了JDK1.6,然后它也开始工作。最后我学习了SSL,然后我解决了这种问题。首先,你需要d从该服务提供商服务器下载证书。然后您确认握手成功。 1.尝试将已签署的文件夹放入服务器 下一条路 2.使用jdk1.7

下一个
3.尝试使用SSL下载有效证书Java 8解决方案:我刚刚遇到了这个问题,通过将远程站点的证书添加到我的Java密钥库解决了这个问题。我的解决方案基于,它基于。这些博客文章解决方案归结为下载一个名为的程序,这是一个可以通过命令l运行的Java类然后继续在Java的密钥库中安装证书

该命令对我非常有效。您只需运行以下命令:

  • javac InstallCert.java
  • java InstallCert[host]:[port]
    (在运行命令时,输入要添加到列表中的证书的给定列表号-可能只有1)
  • keytool-exportcert-alias[host]-1-keystore jssecacerts-storepass changeit-file[host].cer
  • sudo keytool-importcert-alias[host]-keystore[path to system keystore]-storepass changeit-file[host].cer

  • 如果需要,请参阅参考自述文件以获取示例。

    以下是我用于将站点的公共证书安装到系统密钥库中以供使用的解决方案

    使用以下命令下载证书:

    keytool -import -alias "[host]" -keystore [path to keystore] -file [host].crt
    
    unix、linux、mac

    openssl s_client -connect [host]:[port|443] < /dev/null | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > [host].crt
    

    这将允许您从导致异常的站点导入新证书。

    我在尝试从Java代码启动SOAP请求时遇到了这个问题。对我有效的是:

  • 通过点击浏览器中的URL获取服务器证书: 此链接包含获取服务器证书的所有步骤

  • 一旦您有了服务器证书,请遵循以下步骤

  • 复制链接中的文本,如果此链接失效:

    要修复此错误,只需添加服务器证书 到您的可信Java密钥存储。首先,您需要下载 来自服务器的文档

    一旦硬盘中有了证书,就可以将其导入 Java信任存储。将证书导入受信任的Java 密钥存储,您可以使用java“keytool”工具 导航到JRE bin文件夹,在我的例子中,路径是:C:\Program Files\Java\jdk1.7.0\u 75\jre\bin。然后使用keytool命令,如下所示 将证书导入JRE

    keytool-import-alias\u alias\u name\u-keystore..\lib\security\cacerts -文件\u路径\u到\u cer\u文件

    它将要求输入密码。默认情况下,密码为“changeit”。如果 密码不同,您可能无法导入密码 证书


    如果您不需要SSL安全性,则可能需要将其关闭

     /**
       * disable SSL
       */
      private void disableSslVerification() {
        try {
          // Create a trust manager that does not validate certificate chains
          TrustManager[] trustAllCerts = new TrustManager[] {
              new X509TrustManager() {
                public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                  return null;
                }
    
                public void checkClientTrusted(X509Certificate[] certs,
                    String authType) {
                }
    
                public void checkServerTrusted(X509Certificate[] certs,
                    String authType) {
                }
              } };
    
          // Install the all-trusting trust manager
          SSLContext sc = SSLContext.getInstance("SSL");
          sc.init(null, trustAllCerts, new java.security.SecureRandom());
          HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    
          // Create all-trusting host name verifier
          HostnameVerifier allHostsValid = new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
              return true;
            }
          };
    
          // Install the all-trusting host verifier
          HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
        } catch (NoSuchAlgorithmException e) {
          e.printStackTrace();
        } catch (KeyManagementException e) {
          e.printStackTrace();
        }
      }
    

    如果服务器仅发送其叶证书,而未将构建信任链所需的所有链证书发送到根CA,则也可能发生此错误。不幸的是,这是服务器的常见配置错误

    如果大多数浏览器从以前的访问中已经知道丢失的链证书,或者如果叶证书包含权限信息访问(AIA)中CA颁发者的URL,则可能下载丢失的证书,则大多数浏览器都可以解决此问题。但这种行为通常仅限于桌面浏览器和其他工具,因为它们无法建立信任链而失败

    通过将
    com.sun.security.enableaiacaisers
    设置为
    true


    要验证服务器是否正在发送所有链证书,您可以在以下SSL证书验证工具中输入主机,这可能会有所帮助:我也有一个DigiCert,我想可能存在与您描述的相同的问题。在我的情况下,我无法从浏览器导出整个证书链,以将它们全部添加到信任库。Co你可以分享你的方式吗?你使用的是什么浏览器?我相信我是用Firefox来做的,虽然我不记得确切的方法。我以前用过IE。现在我可以用Firefox导出它,并成功地添加到trust stor中
    keytool -import -alias "[host]" -keystore [path to keystore] -file [host].crt
    
     /**
       * disable SSL
       */
      private void disableSslVerification() {
        try {
          // Create a trust manager that does not validate certificate chains
          TrustManager[] trustAllCerts = new TrustManager[] {
              new X509TrustManager() {
                public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                  return null;
                }
    
                public void checkClientTrusted(X509Certificate[] certs,
                    String authType) {
                }
    
                public void checkServerTrusted(X509Certificate[] certs,
                    String authType) {
                }
              } };
    
          // Install the all-trusting trust manager
          SSLContext sc = SSLContext.getInstance("SSL");
          sc.init(null, trustAllCerts, new java.security.SecureRandom());
          HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    
          // Create all-trusting host name verifier
          HostnameVerifier allHostsValid = new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
              return true;
            }
          };
    
          // Install the all-trusting host verifier
          HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
        } catch (NoSuchAlgorithmException e) {
          e.printStackTrace();
        } catch (KeyManagementException e) {
          e.printStackTrace();
        }
      }