Android 自签名客户端 CA 证书认证失败

Android self-signed client side CA certificate authentication fails

Android自签名客户端CA证书认证失败,谁能分享他们处理类似问题的经验?使用相同的凭据,我们可以使用 CURL 客户端让它工作。

我们跟进了this GIST,但是没能通过。

跟随它只是导致我们抛出这个异常:

javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
        at org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:374)

试试下面的代码

// Input stream for self signed CA certificate
InputStream caIs = getInputStream(caCert);
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
X509Certificate certificate = (X509Certificate) certificateFactory.generateCertificate(caIs);
String alias = certificate.getSubjectX500Principal().getName();
Log.d(TAG, String.format("Alias: %s", alias));

// KeyStore for trusted CA certificate(s)
KeyStore trustedStore = KeyStore.getInstance(KeyStore.getDefaultType());
trustedStore.load(null);
trustedStore.setCertificateEntry(alias, certificate);

// Create trust managers to be used for connecting to servics(s)
TrustManagerFactory tmf =  TrustManagerFactory.getInstance("X509");
tmf.init(trustedStore);
TrustManager[] trustManagers = tmf.getTrustManagers();

// KeyStore for X.509 certificate/key
KeyStore keyStore = KeyStore.getInstance("PKCS12");
InputStream clientIs = getInputStream(clientKeyCert);
keyStore.load(clientIs, "password".toCharArray());
KeyManagerFactory kmf = KeyManagerFactory.getInstance("X509");
kmf.init(keyStore, "password".toCharArray());

// Create key managers to be uses for connecting to service(s)
KeyManager[] keyManagers = kmf.getKeyManagers();

// Create the SSL context
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(keyManagers, trustManagers, null);

// Test by connecting ta server proteced by self signed certificate
OkHttpClient client = new OkHttpClient.Builder().sslSocketFactory(sslContext.getSocketFactory()).build();
Call call = client.newCall(new Request.Builder().url("https://testurl.com").build());
Response response = call.execute();
Log.d(TAG, response.message());