解决PKIX问题:unable to find valid certification path to requested target

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/focusjava/article/details/53863807

完整版见https://jadyer.github.io/2012/07/29/ssl-pkix/


话说前几天在测试服务器上遇到了这么个异常

  1. javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed:   
  2. sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target  
就是说找不着安全证书啥的等等烂码七糟的一大堆

接着就拜Google大神,发现一篇文章能被N个人转来转去的,关键文章还不怎么靠谱



后来找到了一个办法,幸运的是在测试环境一弄,这个问题看上去就被解决了



我们要做的就是将所要访问的URL的安全认证证书导入到客户端

下面是获取安全证书的一种方法

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


执行方式:Java InstallCert hostname     eg:Java InstallCert www.cebbank.com

接下来会看到下面的打印信息

  1. java InstallCert www.cebbank.com  
  2. Loading KeyStore /usr/java/jdk1.6.0_31/jre/lib/security/cacerts...  
  3. Opening connection to www.cebbank.com:443...  
  4. Starting SSL handshake...  
  5.   
  6. javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed:   
  7. sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target  
  8.     at com.sun.net.ssl.internal.ssl.Alerts.getSSLException(Alerts.java:174)  
  9.     at com.sun.net.ssl.internal.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1731)  
  10.     at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Handshaker.java:241)  
  11.     at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Handshaker.java:235)  
  12.     at com.sun.net.ssl.internal.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1206)  
  13.     at com.sun.net.ssl.internal.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:136)  
  14.     at com.sun.net.ssl.internal.ssl.Handshaker.processLoop(Handshaker.java:593)  
  15.     at com.sun.net.ssl.internal.ssl.Handshaker.process_record(Handshaker.java:529)  
  16.     at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:925)  
  17.     at com.sun.net.ssl.internal.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1170)  
  18.     at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1197)  
  19.     at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1181)  
  20.     at InstallCert.main(InstallCert.java:102)  
  21. Caused by: sun.security.validator.ValidatorException: PKIX path building failed:   
  22. sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target  
  23.     at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:323)  
  24.     at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:217)  
  25.     at sun.security.validator.Validator.validate(Validator.java:218)  
  26.     at com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:126)  
  27.     at com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:209)  
  28.     at InstallCert$SavingTrustManager.checkServerTrusted(InstallCert.java:198)  
  29.     at com.sun.net.ssl.internal.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1198)  
  30.     ... 8 more  
  31. Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target  
  32.     at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:174)  
  33.     at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:238)  
  34.     at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:318)  
  35.     ... 14 more  
  36.   
  37. Server sent 1 certificate(s):  
  38.   
  39.  1 Subject CN=www.cebbank.com, OU=Terms of use at www.verisign.com/rpa (c)05, OU=CEB, O="China Everbright Bank Co., Ltd", L=Beijing  
  40.    Issuer  CN=VeriSign Class 3 Extended Validation SSL CA, OU=Terms of use at https://www.verisign.com/rpa (c)06, OU=VeriSign Trust Network  
  41.    sha1    5b d2 85 6e b3 a4 2b 07 a2 13 47 b3 be 3e 1f c9 d3 ce 46 57   
  42.    md5     05 d8 ae ee f1 d9 51 63 6d 2f 11 e0 ac d0 e7 d7   
  43.   
  44. Enter certificate to add to trusted keystore or 'q' to quit: [1]  
然后输入1并回车,会看到类似下面的打印信息
  1. [  
  2. [  
  3.   Version: V3  
  4.   Subject: CN=www.cebbank.com, OU=Terms of use at www.verisign.com/rpa (c)05, OU=CEB, O="China Everbright Bank Co., Ltd", L=Beijing  
  5.   Signature Algorithm: SHA1withRSA, OID = 1.2.840.113549.1.1.5  
  6.   
  7.   Key:  Sun RSA public key, 2048 bits  
  8.   modulus: 30831246384548809540705228292841393062583732250993909916355780413722161557074568469738254573472093341710481517139910877  
  9.   public exponent: 65537  
  10.   Validity: [From: Mon Jul 02 08:00:00 CST 2012,  
  11.                To: Thu Jul 03 07:59:59 CST 2014]  
  12.   Issuer: CN=VeriSign Class 3 Extended Validation SSL CA, OU=Terms of use at https://www.verisign.com/rpa (c)06, OU=VeriSign Trust Network  
  13.   SerialNumber: [    5715ab25 6be8fa42 2fa28dd4 601bc732]  
  14.   
  15. Certificate Extensions: 9  
  16. [1]: ObjectId: 1.3.6.1.5.5.7.1.1 Criticality=false  
  17. AuthorityInfoAccess [  
  18.   [  
  19.    accessMethod: 1.3.6.1.5.5.7.48.1  
  20.    accessLocation: URIName: http://ocsp.verisign.com,   
  21.    accessMethod: 1.3.6.1.5.5.7.48.2  
  22.    accessLocation: URIName: http://EVSecure-aia.verisign.com/EVSecure2006.cer]  
  23. ]  
  24.   
  25. [2]: ObjectId: 2.5.29.17 Criticality=false  
  26. SubjectAlternativeName [  
  27.   DNSName: www.cebbank.com  
  28. ]  
  29.   
  30. [3]: ObjectId: 2.5.29.35 Criticality=false  
  31. AuthorityKeyIdentifier [  
  32. KeyIdentifier [  
  33. 0000: FC 8A 50 BA 9E B9 25 5A   7B 55 85 4F 95 00 63 8F  ..P...%Z.U.O..c.  
  34. 0010: E9 58 6B 43                                        .XkC  
  35. ]  
  36.   
  37. ]  
  38.   
  39. [4]: ObjectId: 2.5.29.32 Criticality=false  
  40. CertificatePolicies [  
  41.   [CertificatePolicyId: [2.16.840.1.113733.1.7.23.6]  
  42. [PolicyQualifierInfo: [  
  43.   qualifierID: 1.3.6.1.5.5.7.2.1  
  44.   qualifier: 000016 1C 68 74 74 70 73 3A   2F 2F 77 77 77 2E 76 65  ..https://www.ve  
  45. 001072 69 73 69 67 6E 2E 63   6F 6D 2F 63 70 73        risign.com/cps  
  46.   
  47. ]]  ]  
  48. ]  
  49.   
  50. [5]: ObjectId: 2.5.29.19 Criticality=false  
  51. BasicConstraints:[  
  52.   CA:false  
  53.   PathLen: undefined  
  54. ]  
  55.   
  56. [6]: ObjectId: 1.3.6.1.5.5.7.1.12 Criticality=false  
  57. Extension unknown: DER encoded OCTET string =  
  58. 000004 62 30 60 A1 5E A0 5C   30 5A 30 58 30 56 16 09  .b0`.^.\0Z0X0V..  
  59. 001069 6D 61 67 65 2F 67 69   66 30 21 30 1F 30 07 06  image/gif0!0.0..  
  60. 002005 2B 0E 03 02 1A 04 14   4B 6B B9 28 96 06 0C BB  .+......Kk.(....  
  61. 0030: D0 52 38 9B 29 AC 4B 07   8B 21 05 18 30 26 16 24  .R8.).K..!..0&.$  
  62. 004068 74 74 70 3A 2F 2F 6C   6F 67 6F 2E 76 65 72 69  http://logo.veri  
  63. 005073 69 67 6E 2E 63 6F 6D   2F 76 73 6C 6F 67 6F 31  sign.com/vslogo1  
  64. 0060: 2E 67 69 66                                        .gif  
  65.   
  66.   
  67. [7]: ObjectId: 2.5.29.37 Criticality=false  
  68. ExtendedKeyUsages [  
  69.   serverAuth  
  70.   clientAuth  
  71. ]  
  72.   
  73. [8]: ObjectId: 2.5.29.31 Criticality=false  
  74. CRLDistributionPoints [  
  75.   [DistributionPoint:  
  76.      [URIName: http://EVSecure-crl.verisign.com/EVSecure2006.crl]  
  77. ]]  
  78.   
  79. [9]: ObjectId: 2.5.29.15 Criticality=false  
  80. KeyUsage [  
  81.   DigitalSignature  
  82.   Key_Encipherment  
  83. ]  
  84.   
  85. ]  
  86.   Algorithm: [SHA1withRSA]  
  87.   Signature:  
  88. 000042 0A 89 BF 48 08 1E F4   98 F2 E5 DB 0D 83 EF 37  B...H..........7  
  89. 0010: EC 27 6F 4D 81 69 C6 4A   4C 17 EC 57 F5 48 2A 14  .'oM.i.JL..W.H*.  
  90. 0020: 3C 54 B2 C5 49 39 42 BA   EC 83 78 02 F9 96 6C 63  <T..I9B...x...lc  
  91. 003080 BC 60 61 BB 20 D1 AD   C3 D3 76 47 6F 0C 7B AC  ..`a. ....vGo...  
  92. 004076 B2 C7 2D B1 0A 7A 00   CA 40 38 86 FF 9F 12 F5  v..-..z..@8.....  
  93. 0050: BE 5A E7 42 97 2F DF DE   0C 19 C5 F6 92 58 17 7A  .Z.B./.......X.z  
  94. 0060: 9A 1D 2C 2C DA 8B 83 83   2D BE 07 58 56 36 92 E7  ..,,....-..XV6..  
  95. 0070: B1 F8 A0 B5 00 F4 C3 30   D1 34 37 3D 94 75 28 04  .......0.47=.u(.  
  96. 0080: A2 D8 C3 FE B1 E1 C2 2E   51 A8 6F D5 09 6D 49 DB  ........Q.o..mI.  
  97. 0090: 2E 1D 4B F7 A8 06 30 B4   97 E7 C2 33 26 FD 6A DF  ..K...0....3&.j.  
  98. 00A0: D6 B0 10 A1 F2 73 DD 5A   60 DE 51 5E EA 80 46 86  .....s.Z`.Q^..F.  
  99. 00B0: 25 0B 53 FC C2 57 80 35   09 2D 31 55 28 35 EE 0F  %.S..W.5.-1U(5..  
  100. 00C0: 62 50 4B 12 75 0B 02 9F   2F 0B D2 8A 0D 23 E3 C1  bPK.u.../....#..  
  101. 00D0: 48 28 56 33 E1 DE 31 DD   72 78 15 96 EE 2B A5 1D  H(V3..1.rx...+..  
  102. 00E0: 37 85 1B E5 88 53 80 88   02 6D 90 F3 E6 4A 74 AC  7....S...m...Jt.  
  103. 00F0: D2 CA 0E 04 BC 46 A0 57   34 FA CF 9D E5 D7 0E 4B  .....F.W4......K  
  104.   
  105. ]  
  106.   
  107. Added certificate to keystore 'jssecacerts' using alias 'www.cebbank.com-1'  
同时我们会在当面目录下发现已经生成了一个名为jssecacerts的证书

再将名为jssecacerts的证书拷贝\\%JAVA_HONME%\\jre\\lib\\security\\目录中

最后重启下应用的服务,证书就会生效了。。





补充:有人说生成证书后不用拷贝,直接代码里加句话就行,结果试了一下发现不管用

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

猜你喜欢

转载自blog.csdn.net/focusjava/article/details/53863807