如何使用多个信任源初始化 TrustManagerFactory?
我的应用程序有一个个人密钥库,其中包含受信任的自签名证书,以便在本地网络中使用 - 例如。我希望能够使用本地设置的自签名证书连接到公共站点(例如 google.com)以及本地网络中的站点。mykeystore.jks
这里的问题是,当我连接到 https://google.com 时,路径构建会失败,因为设置我自己的密钥库会覆盖包含与 JRE 捆绑的根 CA 的默认密钥库,并报告异常
sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
但是,如果我将 CA 证书导入到我自己的密钥库() 中,它工作正常。有没有办法同时支持两者?mykeystore.jks
为此,我有自己的信托经理,
public class CustomX509TrustManager implements X509TrustManager {
X509TrustManager defaultTrustManager;
public MyX509TrustManager(KeyStore keystore) {
TrustManagerFactory trustMgrFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustMgrFactory.init(keystore);
TrustManager trustManagers[] = trustMgrFactory.getTrustManagers();
for (int i = 0; i < trustManagers.length; i++) {
if (trustManagers[i] instanceof X509TrustManager) {
defaultTrustManager = (X509TrustManager) trustManagers[i];
return;
}
}
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
try {
defaultTrustManager.checkServerTrusted(chain, authType);
} catch (CertificateException ce) {
/* Handle untrusted certificates */
}
}
}
然后我初始化SSLContext,
TrustManager[] trustManagers =
new TrustManager[] { new CustomX509TrustManager(keystore) };
SSLContext customSSLContext =
SSLContext.getInstance("TLS");
customSSLContext.init(null, trustManagers, null);
并设置插座出厂,
HttpsURLConnection.setDefaultSSLSocketFactory(customSSLContext.getSocketFactory());
主程序,
URL targetServer = new URL(url);
HttpsURLConnection conn = (HttpsURLConnection) targetServer.openConnection();
如果我不设置自己的信任管理器,它就会连接到 https://google.com 就好了。如何获取指向默认密钥存储的“默认信任管理器”?