查看: 1532|回复: 0

[Java代码] java开发https请求ssl不受信任问题解决方法

发表于 2018-2-25 08:00:00

本文主要讨论的是java开发https请求ssl不受信任的解决方法,具体分析及实现代码如下。

java代码中请求https链接的时候,可能会报下面这个错误

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

原因是没有证书。在浏览器中直接使用url访问是可以的,应该是浏览器之前就保存过对应的.cer证书。

解决方法有两种,从目标机器获得有效证书或者忽略证书信任问题。

一、获得目标机器有效证书

1、编译安装证书程序 javac InstallCert.java(代码如下)

  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. * http://blogs.sun.com/andreas/resource/InstallCert.java
  33. * Use:
  34. * java InstallCert hostname
  35. * Example:
  36. *% java InstallCert ecc.fedora.redhat.com
  37. */
  38. import javax.net.ssl.*;
  39. import java.io.*;
  40. import java.security.KeyStore;
  41. import java.security.MessageDigest;
  42. import java.security.cert.CertificateException;
  43. import java.security.cert.X509Certificate;
  44. /**
  45. * Class used to add the server's certificate to the KeyStore
  46. * with your trusted certificates.
  47. */
  48. public class InstallCert {
  49. public static void main(String[] args) throws Exception {
  50. String host;
  51. int port;
  52. char[] passphrase;
  53. if ((args.length == 1) || (args.length == 2)) {
  54. String[] c = args[0].split(":");
  55. host = c[0];
  56. port = (c.length == 1) ? 443 : Integer.parseint(c[1]);
  57. String p = (args.length == 1) ? "changeit" : args[1];
  58. passphrase = p.toCharArray();
  59. } else {
  60. System.out.println("Usage: java InstallCert <host>[:port] [passphrase]");
  61. return;
  62. }
  63. File file = new File("jssecacerts");
  64. if (file.isFile() == false) {
  65. char SEP = File.separatorchar;
  66. File dir = new File(System.getProperty("java.home") + SEP
  67. + "lib" + SEP + "security");
  68. file = new File(dir, "jssecacerts");
  69. if (file.isFile() == false) {
  70. file = new File(dir, "cacerts");
  71. }
  72. }
  73. System.out.println("Loading KeyStore " + file + "...");
  74. InputStream in = new FileInputStream(file);
  75. KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
  76. ks.load(in, passphrase);
  77. in.close();
  78. SSLContext context = SSLContext.getInstance("TLS");
  79. TrustManagerFactory tmf =
  80. TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
  81. tmf.init(ks);
  82. X509TrustManager defaultTrustManager = (X509TrustManager) tmf.getTrustManagers()[0];
  83. SavingTrustManager tm = new SavingTrustManager(defaultTrustManager);
  84. context.init(null, new TrustManager[]{
  85. tm
  86. }
  87. , null);
  88. SSLSocketFactory factory = context.getSocketFactory();
  89. System.out.println("Opening connection to " + host + ":" + port + "...");
  90. SSLSocket socket = (SSLSocket) factory.createSocket(host, port);
  91. socket.setSoTimeout(10000);
  92. try {
  93. System.out.println("Starting SSL handshake...");
  94. socket.startHandshake();
  95. socket.close();
  96. System.out.println();
  97. System.out.println("No errors, certificate is already trusted");
  98. }
  99. catch (SSLException e) {
  100. System.out.println();
  101. e.printStackTrace(System.out);
  102. }
  103. X509Certificate[] chain = tm.chain;
  104. if (chain == null) {
  105. System.out.println("Could not obtain server certificate chain");
  106. return;
  107. }
  108. BufferedReader reader =
  109. new BufferedReader(new InputStreamReader(System.in));
  110. System.out.println();
  111. System.out.println("Server sent " + chain.length + " certificate(s):");
  112. System.out.println();
  113. MessageDigest sha1 = MessageDigest.getInstance("SHA1");
  114. MessageDigest md5 = MessageDigest.getInstance("MD5");
  115. for (int i = 0; i < chain.length; i++) {
  116. X509Certificate cert = chain[i];
  117. System.out.println
  118. (" " + (i + 1) + " Subject " + cert.getSubjectDN());
  119. System.out.println(" Issuer " + cert.getIssuerDN());
  120. sha1.update(cert.getEncoded());
  121. System.out.println(" sha1 " + toHexString(sha1.digest()));
  122. md5.update(cert.getEncoded());
  123. System.out.println(" md5 " + toHexString(md5.digest()));
  124. System.out.println();
  125. }
  126. System.out.println("Enter certificate to add to trusted keystore or 'q' to quit: [1]");
  127. String line = reader.readLine().trim();
  128. int k;
  129. try {
  130. k = (line.length() == 0) ? 0 : Integer.parseint(line) - 1;
  131. }
  132. catch (NumberFormatException e) {
  133. System.out.println("KeyStore not changed");
  134. return;
  135. }
  136. X509Certificate cert = chain[k];
  137. String alias = host + "-" + (k + 1);
  138. ks.setCertificateEntry(alias, cert);
  139. OutputStream out = new FileOutputStream("jssecacerts");
  140. ks.store(out, passphrase);
  141. out.close();
  142. System.out.println();
  143. System.out.println(cert);
  144. System.out.println();
  145. System.out.println
  146. ("Added certificate to keystore 'jssecacerts' using alias '"
  147. + alias + "'");
  148. }
  149. private static final char[] HEXDIGITS = "0123456789abcdef".toCharArray();
  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. private static class SavingTrustManager implements X509TrustManager {
  161. private final X509TrustManager tm;
  162. private X509Certificate[] chain;
  163. SavingTrustManager(X509TrustManager tm) {
  164. this.tm = tm;
  165. }
  166. public X509Certificate[] getAcceptedIssuers() {
  167. throw new UnsupportedOperationException();
  168. }
  169. public void checkClientTrusted(X509Certificate[] chain, String authType)
  170. throws CertificateException {
  171. throw new UnsupportedOperationException();
  172. }
  173. public void checkServerTrusted(X509Certificate[] chain, String authType)
  174. throws CertificateException {
  175. this.chain = chain;
  176. tm.checkServerTrusted(chain, authType);
  177. }
  178. }
  179. }
复制代码

2、运行安装证书程序生成证书

java InstallCert my.hoolai.com

例如:java InstalCert smtp.zhangsan.com:465 admin
如果不加参数password和host的端口号,上面的获取证书程序中默认给的端口号是:443,密码是:changeit

3、根据运行提示信息,输入1,回车,在当前目录下生成名为: jssecacerts 的证书

将证书放置到$JAVA_HOME/jre/lib/security目录下, 切记该JDK的jre是工程所用的环境!!!

或者:

System.setProperty("javax.net.ssl.trustStore", "你的jssecacerts证书路径");

可以更改密码,在security目录下运行命令

keytool -storepasswd -new xxxcom -keystore cacerts

就可以修改密码,修改后使用命令

keytool -list -v -keystore cacerts

查看文件的信息,会提示需要密码才能查看,如果输入密码与修改后的密码匹配,说明修改成功了。

PS:至此这种方式可以成功使用ssl了,另外再补充一下,根据刚才生成的文件jssecacerts,可以生成cer文件,

命令如下

keytool -export -alias xxx.com-1 -keystore jssecacerts -rfc -file xxx.cer

如上,之前的工具类中默认命名别名是加上"-1"。使用InstallCert设置的密码需要跟cacerts文件中的密码一致,

如果修改过密码,就需要修改InstallCert类中对应的密码字符串,否则会有下面这个异常:

java.security.UnrecoverableKeyException: Password verification failed

二、忽略证书信任问题

源码:http://mengyang.iteye.com/blog/575671

一定要注意需要在connection创建之前调用文章里所述的方法,像这个样子:

  1. trustAllHttpsCertificates();
  2. HostnameVerifier hv = new HostnameVerifier() {
  3. public boolean verify(String urlHostName, SSLSession session) {
  4. return true;
  5. }
  6. };
  7. HttpsURLConnection.setDefaultHostnameVerifier(hv);
  8. connection = (HttpURLConnection) url.openConnection();
复制代码

好吧,两种方法都试过有效。

总结

以上就是本文关于java开发https请求ssl不受信任问题解决方法的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!



回复

使用道具 举报