轉載請註明出處:http://www.javashuo.com/article/p-viwudqlc-hs.htmlhtml
最近接一外部接口,接口在本地開發調試及測試都無任何問題(windows下),而上測試環境後測第一次就直接報錯誤,
錯誤是這樣子的:java
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 sun.security.ssl.Alerts.getSSLException(Alerts.java:192) at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1917) at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:301) at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:295) at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1369) at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:156) at sun.security.ssl.Handshaker.processLoop(Handshaker.java:925) at sun.security.ssl.Handshaker.process_record(Handshaker.java:860) at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1043) at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1343) at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1371) at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1355)
enn~,首先那個接口地址是https的,服務器是linux的;以上錯誤其大意是沒法找到及驗證有效證書,再想一想:不對啊,本地jdk和服務器的jdk都是oracle官方jdk 1.8呀,照理說
本地調試沒問題在服務端應該也不會有什麼問題呢~linux
誒~,無論怎麼分析都仍是要解決問題呀,首先我分析到這又兩個問題點:windows
怎麼辦?要求對方檢查證書配置,可能性不大,剩下的就只剩下一種方式:作兼容,就是在請求的時候信任對方的證書。服務器
由於我使用的是CloseableHttpClient,作的請求管理,不如在讓CloseableHttpClient兼容https與http不就行了,尋思一項,搜索一番代碼即成
(這裏只給出核心代碼)session
// 以前 // private static CloseableHttpClient httpClient = HttpClients.custom().build(); // 以後 private static CloseableHttpClient httpClient; static { try { System.out.println("===>01"); // 忽略證書 SSLContextBuilder SslBuilder = new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()); //不進行主機名驗證 SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(SslBuilder.build(), NoopHostnameVerifier.INSTANCE); Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create() .register("http", new PlainConnectionSocketFactory()) .register("https", sslConnectionSocketFactory) .build(); PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry); cm.setMaxTotal(100); httpClient = HttpClients.custom() .setSSLSocketFactory(sslConnectionSocketFactory) .setDefaultCookieStore(new BasicCookieStore()) .setConnectionManager(cm).build(); } catch (Exception e) { e.printStackTrace(); System.out.println("===>02"); httpClient = HttpClients.custom().build(); } }
bingo ~,上線測 。。。oracle
oh~,no,依然是這個錯:app
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 sun.security.ssl.Alerts.getSSLException(Alerts.java:192) ......
待我分析一番,發現上面的代碼僅僅只是爲了避免驗證對方主機,徹底沒有理會證書的錯誤。。。欸~,這是個問題。socket
後我又想起以前上上家公司也有出現過這個問題,哈~,有辦法了,找到源碼把主要的幾句copy過來走走不就行了。ide
核心代碼:
HostnameVerifier hv = new HostnameVerifier() { public boolean verify(String urlHostName, SSLSession session) { return true; } }; private static void trustAllHttpsCertificates() throws Exception { javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[1]; javax.net.ssl.TrustManager tm = new miTM(); trustAllCerts[0] = tm; javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext .getInstance("SSL"); sc.init(null, trustAllCerts, null); javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc .getSocketFactory()); } static class miTM implements javax.net.ssl.TrustManager, javax.net.ssl.X509TrustManager { public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } public boolean isServerTrusted( java.security.cert.X509Certificate[] certs) { return true; } public boolean isClientTrusted( java.security.cert.X509Certificate[] certs) { return true; } public void checkServerTrusted( java.security.cert.X509Certificate[] certs, String authType) throws java.security.cert.CertificateException { return; } public void checkClientTrusted( java.security.cert.X509Certificate[] certs, String authType) throws java.security.cert.CertificateException { return; } } // 在訪問前調用 trustAllHttpsCertificates(); HttpsURLConnection.setDefaultHostnameVerifier(hv);
一整折騰後上線部署測試,啊~,仍是一樣的錯誤。。。
分析代碼,看到,這種處理邏輯只針對自定義SSL證書有效,對於我現有的狀況丁點問題都解決不了
其實業務代碼的什麼都沒改,只是給jdk添加了點兒東西。
主要解決思路是讓jdk忽略指定域名的SSL證書。
//InstallCert.java 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); } } }
具體解決步驟:
javac InstallCert.java
java InstallCert 域名地址
rz => 證書.cer
echo $JAVA_HOME
keytool -import -alias LL1 -keystore $JAVA_HOME/jre/lib/security/cacerts -file /home/證書.cer