带有客户端证书的安卓 Http 请求
我正在尝试使用以下代码向具有客户端证书身份验证的服务器发出请求:
try {
/*** CA Certificate ***/
CertificateFactory cf = CertificateFactory.getInstance("X.509");
InputStream caInput = getResources().openRawResource(R.raw.caserver);
Certificate ca = cf.generateCertificate(caInput);
System.out.println("ca=" + ((X509Certificate) ca).getSubjectDN());
// Create a KeyStore containing our trusted CAs
String keyStoreType = KeyStore.getDefaultType();
KeyStore keyStore = KeyStore.getInstance(keyStoreType);
keyStore.load(null, null);
keyStore.setCertificateEntry("ca", ca);
System.out.println(keyStoreType);
// Create a TrustManager that trusts the CAs in our KeyStore
String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
tmf.init(keyStore);
/*** Client Certificate ***/
KeyStore keyStore12 = KeyStore.getInstance("PKCS12");
InputStream certInput12 = getResources().openRawResource(R.raw.p12client);
keyStore12.load(certInput12, "123456key".toCharArray());
// Create a KeyManager that uses our client cert
String algorithm = KeyManagerFactory.getDefaultAlgorithm();
KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm);
kmf.init(keyStore12, null);
/*** SSL Connection ***/
// Create an SSLContext that uses our TrustManager and our KeyManager
SSLContext context = SSLContext.getInstance("TLS");
context.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
URL url = new URL("https://myurl/test.json");
HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
urlConnection.setSSLSocketFactory(context.getSocketFactory());
System.out.println("Weeeeeeeeeee");
InputStream in = urlConnection.getInputStream(); // this throw exception
}
catch (Exception e) {
e.printStackTrace();
}
当执行到达最后一行时,我获得下一个异常。InputStream in = urlConnection.getInputStream();
System.err: javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
我花了很多时间试图修复此错误,但我找不到任何信息。当我使用带有客户端证书的Web浏览器发出相同的请求时,一切都很好。
有什么帮助吗?提前致谢。
编辑
我按照以下步骤生成证书:
> openssl req -config openssl.cnf -new -x509 -extensions v3_ca -days 3650 -keyout private/caserver.key -out certs/caserver.crt
> openssl req -config openssl.cnf -new -nodes -keyout private/client.key -out client.csr -days 1095
> openssl ca -config openssl.cnf -cert certs/caserver.crt -policy policy_anything -out certs/client.crt -infiles csr/client.csr
> openssl pkcs12 -export -clcerts -in certs/client.crt -inkey private/client.key -out p12client.p12
在我的代码中,我使用caserver.crt和p12client.p12。