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中文网其他相关文章!