我的應用程序有一個個人密鑰庫,其中包含用於本地網絡的可信自簽名證書 - 比如mykeystore.jks
。我希望能夠使用本地供應的自簽名證書連接到公共網站(例如google.com)以及本地網絡中的公共網站。如何使用多個信任來源初始化TrustManagerFactory?
這裏的問題是,當我連接到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
),它工作正常。有沒有辦法支持兩者?
我有自己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 = 新的TrustManager [] {新CustomX509TrustManager(密鑰庫)}; 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就好了。我如何獲得指向默認密鑰庫的「默認信任管理器」?
[JVM中註冊多個密鑰庫]的可能的複製(http://stackoverflow.com/questions/1793979/registering-multiple-keystores-in-jvm) – OrangeDog