Java异常之【sun.security.validator.ValidatorException: PKIX path building failed: sun.security...】

女爷i 2023-10-07 12:23 18阅读 0赞
  1. sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

场景:

Java异常,在做数据采集时,请求https页面,抛出上面问题

解决方案:

生成证书,保证请求正常

代码:

  1. package util;
  2. /**
  3. * @author rodert
  4. * @Date 2020年4月9日 下午3:55:04
  5. * @description 生成jssecacerts 文件,解决在请求https时报错问题
  6. */
  7. /*
  8. * Copyright 2006 Sun Microsystems, Inc. All Rights Reserved.
  9. *
  10. * Redistribution and use in source and binary forms, with or without
  11. * modification, are permitted provided that the following conditions
  12. * are met:
  13. *
  14. * - Redistributions of source code must retain the above copyright
  15. * notice, this list of conditions and the following disclaimer.
  16. *
  17. * - Redistributions in binary form must reproduce the above copyright
  18. * notice, this list of conditions and the following disclaimer in the
  19. * documentation and/or other materials provided with the distribution.
  20. *
  21. * - Neither the name of Sun Microsystems nor the names of its
  22. * contributors may be used to endorse or promote products derived
  23. * from this software without specific prior written permission.
  24. *
  25. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
  26. * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
  27. * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  28. * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  29. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  30. * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  31. * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  32. * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  33. * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  34. * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  35. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  36. */
  37. import java.io.*;
  38. import java.security.*;
  39. import java.security.cert.*;
  40. import javax.net.ssl.*;
  41. public class InstallCert {
  42. public static void main(String[] args) throws Exception {
  43. String host;
  44. int port;
  45. char[] passphrase;
  46. String[] h={"www.cnbeta.com"};//这是要访问的webservice的网址
  47. if ((h.length == 1) || (h.length == 2)) {
  48. String[] c = h[0].split(":");
  49. host = c[0];
  50. port = (c.length == 1) ? 443 : Integer.parseInt(c[1]);
  51. String p = (h.length == 1) ? "changeit" : h[1];
  52. passphrase = p.toCharArray();
  53. } else {
  54. System.out.println("Usage: java InstallCert <host>[:port] [passphrase]");
  55. return;
  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. SSLContext context = SSLContext.getInstance("TLS");
  73. TrustManagerFactory tmf =
  74. TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
  75. tmf.init(ks);
  76. X509TrustManager defaultTrustManager = (X509TrustManager)tmf.getTrustManagers()[0];
  77. SavingTrustManager tm = new SavingTrustManager(defaultTrustManager);
  78. context.init(null, new TrustManager[] {tm}, null);
  79. SSLSocketFactory factory = context.getSocketFactory();
  80. System.out.println("Opening connection to " + host + ":" + port + "...");
  81. SSLSocket socket = (SSLSocket)factory.createSocket(host, port);
  82. socket.setSoTimeout(10000);
  83. try {
  84. System.out.println("Starting SSL handshake...");
  85. socket.startHandshake();
  86. socket.close();
  87. System.out.println();
  88. System.out.println("No errors, certificate is already trusted");
  89. } catch (SSLException e) {
  90. System.out.println();
  91. e.printStackTrace(System.out);
  92. }
  93. X509Certificate[] chain = tm.chain;
  94. if (chain == null) {
  95. System.out.println("Could not obtain server certificate chain");
  96. return;
  97. }
  98. BufferedReader reader =
  99. new BufferedReader(new InputStreamReader(System.in));
  100. System.out.println();
  101. System.out.println("Server sent " + chain.length + " certificate(s):");
  102. System.out.println();
  103. MessageDigest sha1 = MessageDigest.getInstance("SHA1");
  104. MessageDigest md5 = MessageDigest.getInstance("MD5");
  105. for (int i = 0; i < chain.length; i++) {
  106. X509Certificate cert = chain[i];
  107. System.out.println
  108. (" " + (i + 1) + " Subject " + cert.getSubjectDN());
  109. System.out.println(" Issuer " + cert.getIssuerDN());
  110. sha1.update(cert.getEncoded());
  111. System.out.println(" sha1 " + toHexString(sha1.digest()));
  112. md5.update(cert.getEncoded());
  113. System.out.println(" md5 " + toHexString(md5.digest()));
  114. System.out.println();
  115. }
  116. System.out.println("Enter certificate to add to trusted keystore or 'q' to quit: [1]");
  117. String line = reader.readLine().trim();
  118. int k;
  119. try {
  120. k = (line.length() == 0) ? 0 : Integer.parseInt(line) - 1;
  121. } catch (NumberFormatException e) {
  122. System.out.println("KeyStore not changed");
  123. return;
  124. }
  125. X509Certificate cert = chain[k];
  126. String alias = host + "-" + (k + 1);
  127. ks.setCertificateEntry(alias, cert);
  128. OutputStream out = new FileOutputStream("jssecacerts");
  129. ks.store(out, passphrase);
  130. out.close();
  131. System.out.println();
  132. System.out.println(cert);
  133. System.out.println();
  134. System.out.println
  135. ("Added certificate to keystore 'jssecacerts' using alias '"
  136. + alias + "'");
  137. }
  138. private static final char[] HEXDIGITS = "0123456789abcdef".toCharArray();
  139. private static String toHexString(byte[] bytes) {
  140. StringBuilder sb = new StringBuilder(bytes.length * 3);
  141. for (int b : bytes) {
  142. b &= 0xff;
  143. sb.append(HEXDIGITS[b >> 4]);
  144. sb.append(HEXDIGITS[b & 15]);
  145. sb.append(' ');
  146. }
  147. return sb.toString();
  148. }
  149. private static class SavingTrustManager implements X509TrustManager {
  150. private final X509TrustManager tm;
  151. private X509Certificate[] chain;
  152. SavingTrustManager(X509TrustManager tm) {
  153. this.tm = tm;
  154. }
  155. public X509Certificate[] getAcceptedIssuers() {
  156. throw new UnsupportedOperationException();
  157. }
  158. public void checkClientTrusted(X509Certificate[] chain, String authType)
  159. throws CertificateException {
  160. throw new UnsupportedOperationException();
  161. }
  162. public void checkServerTrusted(X509Certificate[] chain, String authType)
  163. throws CertificateException {
  164. this.chain = chain;
  165. tm.checkServerTrusted(chain, authType);
  166. }
  167. }
  168. }

运行后截图:

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQwMzc0NjA0_size_16_color_FFFFFF_t_70

操作:

输入数字:1,会在项目根目录下生成文件,jssecacerts。

注意:

经过测试,在window下不需要加,大概因为浏览器带有证书,在linux服务器没有问题,欢迎留言

发表评论

表情:
评论列表 (有 0 条评论,18人围观)

还没有评论,来说两句吧...

相关阅读