我正在尝试从我的应用程序到内部服务器建立SSL连接。我下载了一个包含所有需要的证书和CA的PKCS12文件。然后我将它加载到我用来进行SSL调用的密钥库中。
当我进行SSL调用时,我收到以下异常:
java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
查看android dev website,看起来这是由于未知的证书颁发机构。
到目前为止,这是我的代码:
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包含在应用资产中?
答案 0 :(得分:0)
您是否没有在清单中设置networkSecurityConfig的问题?