Java 用戶端處理自簽章SSL 憑證
當Java 用戶端遇到具有自簽章憑證的伺服器的SSL 連線時,它可能會失敗並出現以下錯誤:
sun.security.validator.ValidatorException: PKIX path building failed
選項1:新增至信任庫
要建立信任,請將自簽名憑證新增至JVM 信任庫:
<JAVA_HOME>/bin/keytool -import -v -trustcacerts \ -alias server-alias -file server.cer \ -keystore cacerts.jks -keypass changeit \ -storepass changeit
選項2:停用憑證驗證(不推薦)
使用下列指令停用憑證驗證code:
// Trust manager that does not validate certificate chains TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { @Override public void checkClientTrusted(X509Certificate[] certs, String authType) {} @Override public void checkServerTrusted(X509Certificate[] certs, String authType) {} @Override public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } } }; // Install trust manager SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, new SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
但是,不建議停用憑證驗證,因為這會使用戶端容易受到中間人攻擊。
以上是Java 用戶端如何處理自簽章 SSL 憑證?的詳細內容。更多資訊請關注PHP中文網其他相關文章!