0

我正在尝试从我的应用程序到内部服务器建立 SSL 连接。我下载了一个包含所有需要的证书和 CA 的 PKCS12 文件。然后我将它加载到我用来进行 SSL 调用的密钥库中。

当我进行 SSL 调用时,我得到以下异常: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.

查看android dev 网站,看起来这是由于未知的证书颁发机构。

到目前为止,这是我的代码:

private void testConnect(String base64Pkcs) {
    KeyStore keyStore;
    SSLContext sslContext = null;
    TrustManager trustManager = null;
    try {
        keyStore = KeyStore.getInstance("PKCS12");
        writeFile(base64Pkcs);
        if (keyStore != null) {
            keyStore.load(readFile(), DEBUG_CERT_PWD.toCharArray());

            KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            keyManagerFactory.init(keyStore, DEBUG_CERT_PWD.toCharArray());
            KeyManager[] keyManagers = keyManagerFactory.getKeyManagers();

            sslContext = SSLContext.getInstance("TLS");
            TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("X509");
            trustManagerFactory.init(keyStore);
            sslContext.init(keyManagers, trustManagerFactory.getTrustManagers(), null);
            trustManager = trustManagerFactory.getTrustManagers()[0];

            OkHttpClient client = new OkHttpClient.Builder()
                    .sslSocketFactory(sslContext.getSocketFactory(), (X509TrustManager) trustManager)
                    .build();

            final Request request = new Request.Builder().url(getApplication().getString(R.string.https_test_endpoint_url)).build();

            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    Log.e(TAG, "Error while calling the test secure endpoint", e);
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    Log.d(TAG, response.message());
                    if (response.body() != null) {
                        Log.d(TAG, response.body().string());
                    }
                }
            });
        }
    } catch (KeyStoreException | IOException | NoSuchAlgorithmException | CertificateException | UnrecoverableKeyException | KeyManagementException e) {
        //TODO: Handle exceptions
        Log.wtf(TAG, e);
    }
}

我可以通过使用 openSSL 从 PKCS12 文件中手动提取 CA 来使连接正常工作,将其放入我的应用程序资产中,然后使用以下命令加载它:

openssl pkcs12 -in tls.pkcs -cacerts -nokeys -chain -out tls.trust - password pass:mydevpassword`
keyStore.setCertificateEntry("ca", myCaCert);` 

我的问题是我无法从我的应用程序中使用 openSSL 来导出 CA 并将其以编程方式加载到密钥库。有什么办法可以做到这一点,还是我不得不将 CA 包含在应用程序资产中?

4

1 回答 1

0

是您没有在清单中设置 networkSecurityConfig 的问题吗?

https://stackoverflow.com/a/60102517/114265

于 2020-02-07T15:49:18.167 回答