今天,封装HttpClient使用ssl时报一下错误:

  1. 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
  2. at sun.security.ssl.Alerts.getSSLException(Alerts.java:192)
  3. at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1949)
  4. at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:302)
  5. at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:296)
  6. ...
  7. Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
  8. at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:387)
  9. at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:292)
  10. at sun.security.validator.Validator.validate(Validator.java:260)
  11. at sun.security.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:324)
  12. at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:229)

在参考了图解https协议之后,发现这个报错应该就是在客户端“validate crt”的过程中,所以正常的解决思路应该想办法将服务器的证书写入到客户端。

后来在oracle的一篇博客中找到一下的解决方式:

关键步骤:

  1. % java InstallCert _web_site_hostname_
  2. 显示相关的证书信息
  3. 此时输入'q' 则为'退出', '1' 则将添加CA证书。
  4. 将新生成的 "jssecacerts" 移到"$JAVA_HOME/jre/lib/security"

注意:添加CA证书的行为,新生成的jssecacerts则是与旧的jssecacerts叠加的后产生的文件,旧的jssecacerts查找方式如代码所示:

  1. File file = new File("jssecacerts");
  2. if (file.isFile() == false) {
  3. char SEP = File.separatorChar;
  4. File dir = new File(System.getProperty("java.home") + SEP + "lib"
  5. + SEP + "security");
  6. file = new File(dir, "jssecacerts");
  7. if (file.isFile() == false) {
  8. file = new File(dir, "cacerts");
  9. }
  10. }

有点遗憾的是博客中InstallCert下载链接已经失效了。需要异步到github进行下载

代码也留一份到此处:

  1. /*
  2. * Copyright 2006 Sun Microsystems, Inc. All Rights Reserved.
  3. *
  4. * Redistribution and use in source and binary forms, with or without
  5. * modification, are permitted provided that the following conditions
  6. * are met:
  7. *
  8. * - Redistributions of source code must retain the above copyright
  9. * notice, this list of conditions and the following disclaimer.
  10. *
  11. * - Redistributions in binary form must reproduce the above copyright
  12. * notice, this list of conditions and the following disclaimer in the
  13. * documentation and/or other materials provided with the distribution.
  14. *
  15. * - Neither the name of Sun Microsystems nor the names of its
  16. * contributors may be used to endorse or promote products derived
  17. * from this software without specific prior written permission.
  18. *
  19. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
  20. * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
  21. * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  22. * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  23. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  24. * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  25. * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  26. * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  27. * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  28. * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  29. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  30. */
  31. /**
  32. * Originally from:
  33. * http://blogs.sun.com/andreas/resource/InstallCert.java
  34. * Use:
  35. * java InstallCert hostname
  36. * Example:
  37. *% java InstallCert ecc.fedora.redhat.com
  38. */
  39. import javax.net.ssl.*;
  40. import java.io.*;
  41. import java.security.KeyStore;
  42. import java.security.MessageDigest;
  43. import java.security.cert.CertificateException;
  44. import java.security.cert.X509Certificate;
  45. /**
  46. * Class used to add the server's certificate to the KeyStore
  47. * with your trusted certificates.
  48. */
  49. public class InstallCert {
  50. public static void main(String[] args) throws Exception {
  51. String host;
  52. int port;
  53. char[] passphrase;
  54. if ((args.length == 1) || (args.length == 2)) {
  55. String[] c = args[0].split(":");
  56. host = c[0];
  57. port = (c.length == 1) ? 443 : Integer.parseInt(c[1]);
  58. String p = (args.length == 1) ? "changeit" : args[1];
  59. passphrase = p.toCharArray();
  60. } else {
  61. System.out.println("Usage: java InstallCert <host>[:port] [passphrase]");
  62. return;
  63. }
  64. File file = new File("jssecacerts");
  65. if (file.isFile() == false) {
  66. char SEP = File.separatorChar;
  67. File dir = new File(System.getProperty("java.home") + SEP
  68. + "lib" + SEP + "security");
  69. file = new File(dir, "jssecacerts");
  70. if (file.isFile() == false) {
  71. file = new File(dir, "cacerts");
  72. }
  73. }
  74. System.out.println("Loading KeyStore " + file + "...");
  75. InputStream in = new FileInputStream(file);
  76. KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
  77. ks.load(in, passphrase);
  78. in.close();
  79. SSLContext context = SSLContext.getInstance("TLS");
  80. TrustManagerFactory tmf =
  81. TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
  82. tmf.init(ks);
  83. X509TrustManager defaultTrustManager = (X509TrustManager) tmf.getTrustManagers()[0];
  84. SavingTrustManager tm = new SavingTrustManager(defaultTrustManager);
  85. context.init(null, new TrustManager[]{tm}, null);
  86. SSLSocketFactory factory = context.getSocketFactory();
  87. System.out.println("Opening connection to " + host + ":" + port + "...");
  88. SSLSocket socket = (SSLSocket) factory.createSocket(host, port);
  89. socket.setSoTimeout(10000);
  90. try {
  91. System.out.println("Starting SSL handshake...");
  92. socket.startHandshake();
  93. socket.close();
  94. System.out.println();
  95. System.out.println("No errors, certificate is already trusted");
  96. } catch (SSLException e) {
  97. System.out.println();
  98. e.printStackTrace(System.out);
  99. }
  100. X509Certificate[] chain = tm.chain;
  101. if (chain == null) {
  102. System.out.println("Could not obtain server certificate chain");
  103. return;
  104. }
  105. BufferedReader reader =
  106. new BufferedReader(new InputStreamReader(System.in));
  107. System.out.println();
  108. System.out.println("Server sent " + chain.length + " certificate(s):");
  109. System.out.println();
  110. MessageDigest sha1 = MessageDigest.getInstance("SHA1");
  111. MessageDigest md5 = MessageDigest.getInstance("MD5");
  112. for (int i = 0; i < chain.length; i++) {
  113. X509Certificate cert = chain[i];
  114. System.out.println
  115. (" " + (i + 1) + " Subject " + cert.getSubjectDN());
  116. System.out.println(" Issuer " + cert.getIssuerDN());
  117. sha1.update(cert.getEncoded());
  118. System.out.println(" sha1 " + toHexString(sha1.digest()));
  119. md5.update(cert.getEncoded());
  120. System.out.println(" md5 " + toHexString(md5.digest()));
  121. System.out.println();
  122. }
  123. System.out.println("Enter certificate to add to trusted keystore or 'q' to quit: [1]");
  124. String line = reader.readLine().trim();
  125. int k;
  126. try {
  127. k = (line.length() == 0) ? 0 : Integer.parseInt(line) - 1;
  128. } catch (NumberFormatException e) {
  129. System.out.println("KeyStore not changed");
  130. return;
  131. }
  132. X509Certificate cert = chain[k];
  133. String alias = host + "-" + (k + 1);
  134. ks.setCertificateEntry(alias, cert);
  135. OutputStream out = new FileOutputStream("jssecacerts");
  136. ks.store(out, passphrase);
  137. out.close();
  138. System.out.println();
  139. System.out.println(cert);
  140. System.out.println();
  141. System.out.println
  142. ("Added certificate to keystore 'jssecacerts' using alias '"
  143. + alias + "'");
  144. }
  145. private static final char[] HEXDIGITS = "0123456789abcdef".toCharArray();
  146. private static String toHexString(byte[] bytes) {
  147. StringBuilder sb = new StringBuilder(bytes.length * 3);
  148. for (int b : bytes) {
  149. b &= 0xff;
  150. sb.append(HEXDIGITS[b >> 4]);
  151. sb.append(HEXDIGITS[b & 15]);
  152. sb.append(' ');
  153. }
  154. return sb.toString();
  155. }
  156. private static class SavingTrustManager implements X509TrustManager {
  157. private final X509TrustManager tm;
  158. private X509Certificate[] chain;
  159. SavingTrustManager(X509TrustManager tm) {
  160. this.tm = tm;
  161. }
  162. public X509Certificate[] getAcceptedIssuers() {
  163. /**
  164. * This change has been done due to the following resolution advised for Java 1.7+
  165. http://infposs.blogspot.kr/2013/06/installcert-and-java-7.html
  166. **/
  167. return new X509Certificate[0];
  168. //throw new UnsupportedOperationException();
  169. }
  170. public void checkClientTrusted(X509Certificate[] chain, String authType)
  171. throws CertificateException {
  172. throw new UnsupportedOperationException();
  173. }
  174. public void checkServerTrusted(X509Certificate[] chain, String authType)
  175. throws CertificateException {
  176. this.chain = chain;
  177. tm.checkServerTrusted(chain, authType);
  178. }
  179. }
  180. }

解决 java 使用ssl过程中出现"PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target"的更多相关文章

  1. java程序中访问https时,报 PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

    在java中使用https访问数据时报异常: Caused by: sun.security.validator.ValidatorException: PKIX path building fail ...

  2. Maven:sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

    还是记录使用 maven 时遇到的问题. 一.maven报错 maven package 进行打包时出现了以下报错: Non-resolvable parent POM for com.wpbxin: ...

  3. PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

    注:网上搜来的快照,暂未验证 在java代码中请求https链接的时候,可能会报下面这个错误javax.net.ssl.SSLHandshakeException: sun.security.vali ...

  4. Flutter配置环境报错“PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target”

    背景:最近看了很多Flutter漂亮的项目,想要尝试一下.所有环境都搭建好之后,按照文档一步一步配置(抄袭),但始终报如下图错误. PKIX path building failed: sun.sec ...

  5. mvn 编译报错mavn sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested targ

    mavn 编译报错: mavn sun.security.validator.ValidatorException: PKIX path building failed: sun.security.p ...

  6. 报错PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target"

    今天在调用第三方HTTPS接口的时候,一直显示这个报错,然后百度很久,有2种解决方法,一个是说自己手动去导入,第二种用代码忽略证书验证.我用二种方式, 复制即用, public void test2( ...

  7. maven PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path

    maven编译的时候遇到的奇葩问题,  非常奇葩, 所有其他同事都没有遇到 , 仅仅是我遇到了 不清楚是因为用了最新的JDK的缘故(1.8 update91)还是其他什么原因. 总之是证书的问题. 当 ...

  8. sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

    httpclient-4.5.jar 定时发送http包,忽然有一天报错,http证书变更引起的. 之前的代码 try { CloseableHttpClient httpClient = build ...

  9. ES访问遇到sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

    cmd命令cd到jre/bin目录下 输入命令keytool -import -alias 别名 -keystore cacerts -file ‪C://certs//elasticsearch// ...

随机推荐

  1. Webform server.transfer 用法

    server.transfer 特点: 1:大家熟悉的一个特点,用server.transfer 跳转到新页面时,浏览器的地址是没有改变的(因为重定向完全在服务器端进行,浏览器根本不知道服务器已经执行 ...

  2. CSS中LI圆点样式li {list-style-type:符号名称}

    css中用list-style-type指定列表(lists)前面符号,如下: li {list-style-type:符号名称} 符号名称可用的值为: disc : CSS1 实心圆 circle ...

  3. UIPickerView滚轮选择器视图

    //必须实现两个协议 //数据源协议必须实现的两个方法 //选取器的输出借口singlePicker,并在故事版中选择该选取器将dataSource和delegate拖入视图控制器与之关联 //@pr ...

  4. Linux操作系统备份之三:通过二进制拷贝(dd)方式实现Linux操作系统数据的备份

    前面有两篇文章,<Linux操作系统备份之一:使用LVM快照实现Linux操作系统数据的在线备份>和<Linux操作系统备份之二:通过tar拷贝分区实现Linux操作数据的在线备份& ...

  5. 夺命雷公狗-----React_native---5---初步读懂代码模式

    我们的代码一般导出会用两种方式,如下所示: 这两种方法都是可以的.... 引入方式其实也是很简单的,如下所示: 这样即可...

  6. 移动设备如何打开RMS加密的文档

    关键字:RMS. AZure RMS.IPhone.Android.Office365.Sharepoint.Exchange 最近总是碰到要求用苹果手机及安卓手机阅读RMS加密文档的需求,经过查找相 ...

  7. window10 安装SVN 提示权限问题

     http://www.yishimei.cn/network/551.html 经常在网上看到有同学反映,他们在控制面板里卸载软件的时候,总是会出现2502.2503错误代码的问题,并且这个问题大多 ...

  8. Dynamics AX 2012 R2 AIF 内部异常 output session was auto-closes

    今天调用AIF出现异常,异常信息如下 This chanel can no longer be used to send message as the output session was auto- ...

  9. Linux:-拷贝或传送文件的技巧

    <---拷贝目录如何做到排除文件?常用命令cp,用法比较LOW---> tar -cf - ./* --exclude="nohup.out" | (cd /opt/ ...

  10. Linux中profile、bashrc、bash_profile之间的区别和联系

    /etc/profile:此文件为系统的每个用户设置环境信息,当用户第一次登录时,该文件被执行.并从/etc/profile.d目录的配置文件中搜集shell的设置. 英文描述为: # /etc/pr ...