解决PKIX(PKIX path building failed) 问题 unable to find valid certification path to requested target(示例代
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了解决PKIX(PKIX path building failed) 问题 unable to find valid certification path to requested target(示例代相关的知识,希望对你有一定的参考价值。
最近在写java的一个服务,需要给远程服务器发送post请求,认证方式为Basic Authentication,在请求过程中出现了
PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target的错误,于是开始搜索并得到解决,
下面总结一下解决过程:
我们要做的就是将所要访问的URL的安全认证证书导入到客户端中,以下就是获取安全证书的一种方法:
1.首先新建一个java类,命名为 InstallCert.java,将下面内容保存到文件中
/* * Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of Sun Microsystems nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import java.io.*; import java.net.URL; import java.security.*; import java.security.cert.*; import javax.net.ssl.*; public class InstallCert { public static void main(String[] args) throws Exception { String host; int port; char[] passphrase; if ((args.length == 1) || (args.length == 2)) { String[] c = args[0].split(":"); host = c[0]; port = (c.length == 1) ? 443 : Integer.parseInt(c[1]); String p = (args.length == 1) ? "changeit" : args[1]; passphrase = p.toCharArray(); } else { System.out.println("Usage: java InstallCert <host>[:port] [passphrase]"); return; } File file = new File("jssecacerts"); if (file.isFile() == false) { char SEP = File.separatorChar; File dir = new File(System.getProperty("java.home") + SEP + "lib" + SEP + "security"); file = new File(dir, "jssecacerts"); if (file.isFile() == false) { file = new File(dir, "cacerts"); } } System.out.println("Loading KeyStore " + file + "..."); InputStream in = new FileInputStream(file); KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(in, passphrase); in.close(); SSLContext context = SSLContext.getInstance("TLS"); TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(ks); X509TrustManager defaultTrustManager = (X509TrustManager)tmf.getTrustManagers()[0]; SavingTrustManager tm = new SavingTrustManager(defaultTrustManager); context.init(null, new TrustManager[] {tm}, null); SSLSocketFactory factory = context.getSocketFactory(); System.out.println("Opening connection to " + host + ":" + port + "..."); SSLSocket socket = (SSLSocket)factory.createSocket(host, port); socket.setSoTimeout(10000); try { System.out.println("Starting SSL handshake..."); socket.startHandshake(); socket.close(); System.out.println(); System.out.println("No errors, certificate is already trusted"); } catch (SSLException e) { System.out.println(); e.printStackTrace(System.out); } X509Certificate[] chain = tm.chain; if (chain == null) { System.out.println("Could not obtain server certificate chain"); return; } BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); System.out.println(); System.out.println("Server sent " + chain.length + " certificate(s):"); System.out.println(); MessageDigest sha1 = MessageDigest.getInstance("SHA1"); MessageDigest md5 = MessageDigest.getInstance("MD5"); for (int i = 0; i < chain.length; i++) { X509Certificate cert = chain[i]; System.out.println (" " + (i + 1) + " Subject " + cert.getSubjectDN()); System.out.println(" Issuer " + cert.getIssuerDN()); sha1.update(cert.getEncoded()); System.out.println(" sha1 " + toHexString(sha1.digest())); md5.update(cert.getEncoded()); System.out.println(" md5 " + toHexString(md5.digest())); System.out.println(); } System.out.println("Enter certificate to add to trusted keystore or ‘q‘ to quit: [1]"); String line = reader.readLine().trim(); int k; try { k = (line.length() == 0) ? 0 : Integer.parseInt(line) - 1; } catch (NumberFormatException e) { System.out.println("KeyStore not changed"); return; } X509Certificate cert = chain[k]; String alias = host + "-" + (k + 1); ks.setCertificateEntry(alias, cert); OutputStream out = new FileOutputStream("jssecacerts"); ks.store(out, passphrase); out.close(); System.out.println(); System.out.println(cert); System.out.println(); System.out.println ("Added certificate to keystore ‘jssecacerts‘ using alias ‘" + alias + "‘"); } private static final char[] HEXDIGITS = "0123456789abcdef".toCharArray(); private static String toHexString(byte[] bytes) { StringBuilder sb = new StringBuilder(bytes.length * 3); for (int b : bytes) { b &= 0xff; sb.append(HEXDIGITS[b >> 4]); sb.append(HEXDIGITS[b & 15]); sb.append(‘ ‘); } return sb.toString(); } private static class SavingTrustManager implements X509TrustManager { private final X509TrustManager tm; private X509Certificate[] chain; SavingTrustManager(X509TrustManager tm) { this.tm = tm; } public X509Certificate[] getAcceptedIssuers() { throw new UnsupportedOperationException(); } public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { throw new UnsupportedOperationException(); } public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { this.chain = chain; tm.checkServerTrusted(chain, authType); } } }
2.我是将文件放到D盘根目录,打开cmd命令开始编译此java文件
首先在cmd中进入到java的安装目录,然后用 javac 来编译文件
文件编译完成后会在 同一个目录下成两个类(InstallCert.class,InstallCert$SavingTrustManager.class)
3. 用命令执行 InstallCert.class ,命令方式为:java InstallCert hostname (hostname为请求服务器的地址) 比如:java InstallCert www.cebbank.com
接下来会看到如下的打印信息
java InstallCert www.cebbank.com Loading KeyStore /usr/java/jdk1.6.0_31/jre/lib/security/cacerts... Opening connection to www.cebbank.com:443... Starting SSL handshake... 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 at com.sun.net.ssl.internal.ssl.Alerts.getSSLException(Alerts.java:174) at com.sun.net.ssl.internal.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1731) at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Handshaker.java:241) at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Handshaker.java:235) at com.sun.net.ssl.internal.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1206) at com.sun.net.ssl.internal.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:136) at com.sun.net.ssl.internal.ssl.Handshaker.processLoop(Handshaker.java:593) at com.sun.net.ssl.internal.ssl.Handshaker.process_record(Handshaker.java:529) at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:925) at com.sun.net.ssl.internal.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1170) at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1197) at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1181) at InstallCert.main(InstallCert.java:102) Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:323) at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:217) at sun.security.validator.Validator.validate(Validator.java:218) at com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:126) at com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:209) at InstallCert$SavingTrustManager.checkServerTrusted(InstallCert.java:198) at com.sun.net.ssl.internal.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1198) ... 8 more Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:174) at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:238) at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:318) ... 14 more Server sent 1 certificate(s): 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 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 sha1 5b d2 85 6e b3 a4 2b 07 a2 13 47 b3 be 3e 1f c9 d3 ce 46 57 md5 05 d8 ae ee f1 d9 51 63 6d 2f 11 e0 ac d0 e7 d7 Enter certificate to add to trusted keystore or ‘q‘ to quit: [1]
然后输入 1 并回车,会看到类似下面的打印信息
[ [ Version: V3 Subject: CN=service.uvpan.com Signature Algorithm: SHA256withRSA, OID = 1.2.840.113549.1.1.11 Key: Sun RSA public key, 2048 bits modulus: 231788198608876119472114482789500949944227474346827557770462853229741747853549763950620726235232342519069911673680471226497
634308961543332172169137368578604955021528942246111911815409088185549136660837904968530263770617490825071029281708805581287573146382156
988547125413531430759608525852511318423406844445234168173367907113071152809771040697029566469752955209390398103399068938288619962718137
3674868501753185286836657606758066747142393165835640040523017880256030555956691753813436498142943955042622976588004799964700139167420116
5072543279163545224784152093458502039083825500983120089499582892294317486244911305201899 public exponent: 65537 Validity: [From: Wed Jun 22 15:36:32 CST 2016, To: Fri Jun 22 15:36:32 CST 2018] Issuer: CN=WoSign CA Free SSL Certificate G2, O=WoSign CA Limited, C=CN SerialNumber: [ 4c4a82ba 115c1eed fd6861f6 e8e6c15d] Certificate Extensions: 9 [1]: ObjectId: 1.3.6.1.5.5.7.1.1 Criticality=false AuthorityInfoAccess [ [ accessMethod: ocsp accessLocation: URIName: http://ocsp1.wosign.com/ca6/server1/free , accessMethod: caIssuers accessLocation: URIName: http://aia1.wosign.com/ca6.server1.free.cer ] ] [2]: ObjectId: 2.5.29.35 Criticality=false AuthorityKeyIdentifier [ KeyIdentifier [ 0000: D2 A7 16 20 7C AF D9 95 9E EB 43 0A 19 F2 E0 B9 ... ......C..... 0010: 74 0E A8 C7 t... ] ] [3]: ObjectId: 2.5.29.19 Criticality=false BasicConstraints:[ CA:false PathLen: undefined ] [4]: ObjectId: 2.5.29.31 Criticality=false CRLDistributionPoints [ [DistributionPoint: [URIName: http://crls1.wosign.com/ca6-server1-free.crl] ]] [5]: ObjectId: 2.5.29.32 Criticality=false CertificatePolicies [ [CertificatePolicyId: [2.23.140.1.2.1] [] ] [CertificatePolicyId: [1.3.6.1.4.1.36305.1.1.2] [PolicyQualifierInfo: [ qualifierID: 1.3.6.1.5.5.7.2.1 qualifier: 0000: 16 1D 68 74 74 70 3A 2F 2F 77 77 77 2E 77 6F 73 ..http://www.wos 0010: 69 67 6E 2E 63 6F 6D 2F 70 6F 6C 69 63 79 2F ign.com/policy/ ]] ] ] [6]: ObjectId: 2.5.29.37 Criticality=false ExtendedKeyUsages [ clientAuth serverAuth ] [7]: ObjectId: 2.5.29.15 Criticality=true KeyUsage [ DigitalSignature Key_Encipherment ] [8]: ObjectId: 2.5.29.17 Criticality=false SubjectAlternativeName [ DNSName: service.uvpan.com ] [9]: ObjectId: 2.5.29.14 Criticality=false SubjectKeyIdentifier [ KeyIdentifier [ 0000: 41 1E C2 CA C5 C6 DE 3A 19 02 3B 0B EE 3B 22 09 A......:..;..;". 0010: 76 43 C3 56 vC.V ] ] ] Algorithm: [SHA256withRSA] Signature: 0000: 2C AC BE 2D 4A 38 2F 1F AE 80 38 F3 64 7B 58 BF ,..-J8/...8.d.X. 0010: B9 91 8C B6 59 09 42 95 9A BE 50 FD 22 A9 13 DA ....Y.B...P."... 0020: C2 ED 6B 32 88 DB E2 A6 A1 1C 96 A0 02 B7 1D 2E ..k2............ 0030: 93 9C B7 6C BB F3 FB 92 AF F6 3E 71 5A 0B A5 89 ...l......>qZ... 0040: 46 1F 4F 5F 06 6B 0B FF 77 B2 B2 E2 31 CA 09 86 F.O_.k..w...1... 0050: 78 64 A6 2B DA A1 8D EA 93 DF E8 BB CF F3 55 F9 xd.+..........U. 0060: 10 B0 BA 8D D2 04 7A EB D4 66 12 D6 03 86 65 D8 ......z..f....e. 0070: 2A 55 EB 6A 92 28 98 52 B8 BC A0 8A 66 EF FE E5 *U.j.(.R....f... 0080: 48 1A 01 9B 14 CB D9 66 62 1C 22 D5 5A C1 00 05 H......fb.".Z... 0090: 00 8C 48 63 F2 E8 42 A8 3D 66 38 FC F0 5A B3 36 ..Hc..B.=f8..Z.6 00A0: C9 47 C1 13 2A CC 06 71 AB 28 28 04 66 80 11 FE .G..*..q.((.f... 00B0: F6 C0 97 45 85 6B B9 EC 6A 7C E8 EF AD 95 F4 EC ...E.k..j....... 00C0: BF FF 95 39 D0 45 EB CD 29 E0 84 45 7A 29 F0 B0 ...9.E..)..Ez).. 00D0: 9C F8 E2 72 F7 50 8C AF FE 9D F5 1E 78 A9 06 A9 ...r.P......x... 00E0: F5 7E 6D B7 AF B2 72 D7 C9 5C FD FC 41 95 FA 1D ..m...r..\\..A... 00F0: E8 AC D5 1C 52 86 67 3D 56 56 A5 B9 87 38 86 20 ....R.g=VV...8. ] Added certificate to keystore ‘jssecacerts‘ using alias ‘service.uvpan.com-1‘
同时我们会在当前目录下发现已经生成了一个名为jssecacerts的证书
再将名为jssecacerts的证书拷贝\\\\%JAVA_HONME%\\\\jre\\\\lib\\\\security\\\\目录中
最后重启下应用的服务,证书就会生效了,就可以正常发送请求了(重启tomcat就可以了)。。