解决 sun.security.validator.ValidatorException: PKIX path building failed:

错误信息:

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

问题原因:

源应用程序不信任目标应用程序的证书,因为在源应用程序的JVM信任库中找不到该证书或证书链。

解决办法: 

  • 写一个安全程序专门用于获取安全证书:
  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. import java.io.*;
  33. import java.net.URL;
  34.  
  35. import java.security.*;
  36. import java.security.cert.*;
  37.  
  38. import javax.net.ssl.*;
  39.  
  40. public class InstallCert {
  41.  
  42. public static void main(String[] args) throws Exception {
  43. String host;
  44. int port;
  45. char[] passphrase;
  46. if ((args.length == 1) || (args.length == 2)) {
  47. String[] c = args[0].split(":");
  48. host = c[0];
  49. port = (c.length == 1) ? 443 : Integer.parseInt(c[1]);
  50. String p = (args.length == 1) ? "changeit" : args[1];
  51. passphrase = p.toCharArray();
  52. } else {
  53. System.out.println("Usage: java InstallCert <host>[:port] [passphrase]");
  54. return;
  55. }
  56.  
  57. File file = new File("jssecacerts");
  58. if (file.isFile() == false) {
  59. char SEP = File.separatorChar;
  60. File dir = new File(System.getProperty("java.home") + SEP
  61. + "lib" + SEP + "security");
  62. file = new File(dir, "jssecacerts");
  63. if (file.isFile() == false) {
  64. file = new File(dir, "cacerts");
  65. }
  66. }
  67. System.out.println("Loading KeyStore " + file + "...");
  68. InputStream in = new FileInputStream(file);
  69. KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
  70. ks.load(in, passphrase);
  71. in.close();
  72.  
  73. SSLContext context = SSLContext.getInstance("TLS");
  74. TrustManagerFactory tmf =
  75. TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
  76. tmf.init(ks);
  77. X509TrustManager defaultTrustManager = (X509TrustManager)tmf.getTrustManagers()[0];
  78. SavingTrustManager tm = new SavingTrustManager(defaultTrustManager);
  79. context.init(null, new TrustManager[] {tm}, null);
  80. SSLSocketFactory factory = context.getSocketFactory();
  81.  
  82. System.out.println("Opening connection to " + host + ":" + port + "...");
  83. SSLSocket socket = (SSLSocket)factory.createSocket(host, port);
  84. socket.setSoTimeout(10000);
  85. try {
  86. System.out.println("Starting SSL handshake...");
  87. socket.startHandshake();
  88. socket.close();
  89. System.out.println();
  90. System.out.println("No errors, certificate is already trusted");
  91. } catch (SSLException e) {
  92. System.out.println();
  93. e.printStackTrace(System.out);
  94. }
  95.  
  96. X509Certificate[] chain = tm.chain;
  97. if (chain == null) {
  98. System.out.println("Could not obtain server certificate chain");
  99. return;
  100. }
  101.  
  102. BufferedReader reader =
  103. new BufferedReader(new InputStreamReader(System.in));
  104.  
  105. System.out.println();
  106. System.out.println("Server sent " + chain.length + " certificate(s):");
  107. System.out.println();
  108. MessageDigest sha1 = MessageDigest.getInstance("SHA1");
  109. MessageDigest md5 = MessageDigest.getInstance("MD5");
  110. for (int i = 0; i < chain.length; i++) {
  111. X509Certificate cert = chain[i];
  112. System.out.println
  113. (" " + (i + 1) + " Subject " + cert.getSubjectDN());
  114. System.out.println(" Issuer " + cert.getIssuerDN());
  115. sha1.update(cert.getEncoded());
  116. System.out.println(" sha1 " + toHexString(sha1.digest()));
  117. md5.update(cert.getEncoded());
  118. System.out.println(" md5 " + toHexString(md5.digest()));
  119. System.out.println();
  120. }
  121.  
  122. System.out.println("Enter certificate to add to trusted keystore or 'q' to quit: [1]");
  123. String line = reader.readLine().trim();
  124. int k;
  125. try {
  126. k = (line.length() == 0) ? 0 : Integer.parseInt(line) - 1;
  127. } catch (NumberFormatException e) {
  128. System.out.println("KeyStore not changed");
  129. return;
  130. }
  131.  
  132. X509Certificate cert = chain[k];
  133. String alias = host + "-" + (k + 1);
  134. ks.setCertificateEntry(alias, cert);
  135.  
  136. OutputStream out = new FileOutputStream("jssecacerts");
  137. ks.store(out, passphrase);
  138. out.close();
  139.  
  140. System.out.println();
  141. System.out.println(cert);
  142. System.out.println();
  143. System.out.println
  144. ("Added certificate to keystore 'jssecacerts' using alias '"
  145. + alias + "'");
  146. }
  147.  
  148. private static final char[] HEXDIGITS = "0123456789abcdef".toCharArray();
  149.  
  150. private static String toHexString(byte[] bytes) {
  151. StringBuilder sb = new StringBuilder(bytes.length * 3);
  152. for (int b : bytes) {
  153. b &= 0xff;
  154. sb.append(HEXDIGITS[b >> 4]);
  155. sb.append(HEXDIGITS[b & 15]);
  156. sb.append(' ');
  157. }
  158. return sb.toString();
  159. }
  160.  
  161. private static class SavingTrustManager implements X509TrustManager {
  162.  
  163. private final X509TrustManager tm;
  164. private X509Certificate[] chain;
  165.  
  166. SavingTrustManager(X509TrustManager tm) {
  167. this.tm = tm;
  168. }
  169.  
  170. public X509Certificate[] getAcceptedIssuers() {
  171. throw new UnsupportedOperationException();
  172. }
  173.  
  174. public void checkClientTrusted(X509Certificate[] chain, String authType)
  175. throws CertificateException {
  176. throw new UnsupportedOperationException();
  177. }
  178.  
  179. public void checkServerTrusted(X509Certificate[] chain, String authType)
  180. throws CertificateException {
  181. this.chain = chain;
  182. tm.checkServerTrusted(chain, authType);
  183. }
  184. }
  185.  
  186. }
  • 将代码保存为InstallCert.java文件,并通过javac InstallCert.java 命令编译Java程序
  • 执行 java InstallCert hostname 命令,如:java InstallCert 192.168.1.137:8443(要访问的目标程序的IP地址和端口),然后会看到如下信息:
  1. java InstallCert ecc.fedora.redhat.com
  2. Loading KeyStore /usr/jdk/instances/jdk1.5.0/jre/lib/security/cacerts...
  3. Opening connection to ecc.fedora.redhat.com:443...
  4. Starting SSL handshake...
  5.  
  6. 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
  7. at com.sun.net.ssl.internal.ssl.Alerts.getSSLException(Alerts.java:150)
  8. at com.sun.net.ssl.internal.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1476)
  9. at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Handshaker.java:174)
  10. at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Handshaker.java:168)
  11. at com.sun.net.ssl.internal.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:846)
  12. at com.sun.net.ssl.internal.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:106)
  13. at com.sun.net.ssl.internal.ssl.Handshaker.processLoop(Handshaker.java:495)
  14. at com.sun.net.ssl.internal.ssl.Handshaker.process_record(Handshaker.java:433)
  15. at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:815)
  16. at com.sun.net.ssl.internal.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1025)
  17. at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1038)
  18. at InstallCert.main(InstallCert.java:63)
  19. Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
  20. at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:221)
  21. at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:145)
  22. at sun.security.validator.Validator.validate(Validator.java:203)
  23. at com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:172)
  24. at InstallCert$SavingTrustManager.checkServerTrusted(InstallCert.java:158)
  25. at com.sun.net.ssl.internal.ssl.JsseX509TrustManager.checkServerTrusted(SSLContextImpl.java:320)
  26. at com.sun.net.ssl.internal.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:839)
  27. ... 7 more
  28. Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
  29. at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:236)
  30. at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:194)
  31. at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:216)
  32. ... 13 more
  33.  
  34. Server sent 2 certificate(s):
  35.  
  36. 1 Subject CN=ecc.fedora.redhat.com, O=example.com, C=US
  37. Issuer CN=Certificate Shack, O=example.com, C=US
  38. sha1 2e 7f 76 9b 52 91 09 2e 5d 8f 6b 61 39 2d 5e 06 e4 d8 e9 c7
  39. md5 dd d1 a8 03 d7 6c 4b 11 a7 3d 74 28 89 d0 67 54
  40.  
  41. 2 Subject CN=Certificate Shack, O=example.com, C=US
  42. Issuer CN=Certificate Shack, O=example.com, C=US
  43. sha1 fb 58 a7 03 c4 4e 3b 0e e3 2c 40 2f 87 64 13 4d df e1 a1 a6
  44. md5 72 a0 95 43 7e 41 88 18 ae 2f 6d 98 01 2c 89 68
  45.  
  46. Enter certificate to add to trusted keystore or 'q' to quit: [1]
  •  直接输入1,然后会在相应的目录下产生一个名为‘jssecacerts’的证书,将证书copy到$JAVA_HOME/jre/lib/security目录下,或者通过执行:

System.setProperty("javax.net.ssl.trustStore", "D:\UTA\DOC_E_Health_XML\Keystore\jssecacerts

    • 重启程序即可解决
原文地址:https://www.cnblogs.com/ldsweely/p/13514577.html