小编典典
这里基本上有两个选择:将自签名证书添加到JVM信任库中,或将客户端配置为
选项1
从浏览器导出证书,并将其导入到JVM信任库中(以建立信任链):
\bin\keytool -import -v -trustcacerts
-alias server-alias -file server.cer
-keystore cacerts.jks -keypass changeit
-storepass changeit
选项2
禁用证书验证:
// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[] {
new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
public void checkClientTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
}
};
// Install the all-trusting trust manager
try {
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (GeneralSecurityException e) {
}
// Now you can access an https URL without having the certificate in the truststore
try {
URL url = new URL("https://hostname/index.html");
} catch (MalformedURLException e) {
}
请注意,我完全不建议使用选项2。禁用信任管理器会破坏SSL的某些部分,并使您容易受到中间攻击的攻击。首选选项1,或者甚至更好,让服务器使用由知名CA签名的“真实”证书。
2020-02-26