我的应用程序有一个个人 keystore ,其中包含用于本地网络的受信任的自签名证书 - 比如 mykeystore.jks
。我希望能够使用本地提供的自签名证书连接到公共(public)站点(比如 google.com)以及本地网络中的站点。
这里的问题是,当我连接到 https://google.com 时,路径构建失败,因为设置我自己的 keystore 覆盖了包含与 JRE 捆绑的根 CA 的默认 keystore ,报告异常
sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
但是,如果我将 CA 证书导入我自己的 keystore (mykeystore.jks
),它就可以正常工作。有没有办法同时支持这两者?
为此,我有自己的 TrustManger,
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正好。如何获得指向默认 keystore 的“默认信任管理器”?
最佳答案
在 trustMgrFactory.init(keystore);
中,您使用自己的个人 keystore 而不是系统默认 keystore 配置 defaultTrustManager。
根据阅读 sun.security.ssl.TrustManagerFactoryImpl 的源代码,看起来 trustMgrFactory.init((KeyStore) null);
会完全满足您的需要(加载系统默认 keystore ) ),并且基于快速测试,它似乎对我有用。
关于java - 如何使用多个信任源初始化 TrustManagerFactory?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23144353/