如何使用多个信任源初始化 TrustManagerFactory?

2022-09-01 22:53:46

我的应用程序有一个个人密钥库,其中包含受信任的自签名证书,以便在本地网络中使用 - 例如。我希望能够使用本地设置的自签名证书连接到公共站点(例如 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 就好了。如何获取指向默认密钥存储的“默认信任管理器”?


答案 1

在配置缺省信任管理器时,您将使用自己的个人密钥库(而不是系统缺省密钥库)进行配置。trustMgrFactory.init(keystore);

基于阅读sun.security.ssl.TrustManagerFactoryImpl的源代码,它看起来完全符合您的需求(加载系统默认密钥库),并且基于快速测试,它似乎对我有用。trustMgrFactory.init((KeyStore) null);


答案 2

答案是我如何理解如何做到这一点。如果您只想接受系统 CA 证书以及证书的自定义密钥库,我使用一些方便的方法将其简化为单个类。此处提供完整代码:

https://gist.github.com/HughJeffner/6eac419b18c6001aeadb

KeyStore keystore; // Get your own keystore here
SSLContext sslContext = SSLContext.getInstance("TLS");
TrustManager[] tm = CompositeX509TrustManager.getTrustManagers(keystore);
sslContext.init(null, tm, null);