Android的自签名证书:信任锚认证路径没有找到
我知道这个主题在很多地方讨论,但我经历了几乎所有的人去了之后,我决定创建我的第一个问题StackOverflow上...Android的自签名证书:信任锚认证路径没有找到
的问题是以下内容:
我想连接到一个安全的web服务(HTTPS),其使用证书来限制访问,和用户名/密码对用户进行认证。所以我有一个客户端证书(p12文件)和一个服务器证书(pem或der文件)。我尝试使用HttpURLConnection类,因为据我所知,Apache库不会在Android上受到支持。
所以这是我实现(serverCert和clientCert是完整路径到我的文件):
// Load CAs from our reference to the file
CertificateFactory cf = CertificateFactory.getInstance("X.509");
InputStream caInput = new BufferedInputStream(new FileInputStream(serverCert));
X509Certificate serverCertificate;
try {
serverCertificate = (X509Certificate)cf.generateCertificate(caInput);
System.out.println("ca=" + serverCertificate.getSubjectDN());
} finally {
caInput.close();
}
Log.d(TAG, "Server Cert: " + serverCertificate);
// Create a KeyStore containing our trusted CAs
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
trustStore.load(null);
trustStore.setCertificateEntry("my ca", serverCertificate);
//Load the Client certificate in the keystore
KeyStore keyStore = KeyStore.getInstance("PKCS12");
FileInputStream fis = new FileInputStream(clientCert);
keyStore.load(fis,CLIENT_PASSWORD);
// Create a TrustManager that trusts the CAs in our KeyStore
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(trustStore);
//Build the SSL Context
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(keyStore, pref.getString(Constants.clientCertificatePassword, "").toCharArray
());
//Create the SSL context
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
...
//And later, we use that sslContext to initiatize the socketFactory
urlConnection = (HttpsURLConnection) requestedUrl.openConnection();
urlConnection.setSSLSocketFactory(CertificateManager.getInstance().getSslContext().getSocketFactory());
...
因此,我可以创造我的SSLContext,并显示我的两个证书的内容。但是,当我尝试执行我的HTTPS连接时,出现以下异常:
09-23 13:43:30.283:W/System.err(19422):javax.net.ssl.SSLHandshakeException:java.security。 cert.CertPathValidatorException:找不到证书路径的信任锚点。
你们中的一个曾经遇到以下错误吗?你的解决方案是什么?
这些网站我的经历(没有成功):
http://blog.chariotsolutions.com/2013/01/https-with-client-certificates-on.html
http://nelenkov.blogspot.ch/2011/12/using-custom-certificate-trust-store-on.html
在你的代码的创建和初始化SSLContext
,但不使用它。也许你应该更换:
urlConnection.setSSLSocketFactory(CertificateManager.getInstance().getSslContext().getSocketFactory());
通过
urlConnection.setSSLSocketFactory(sslContext.getSocketFactory());
我也建议你如果可能的选项-Djavax.net.debug=all
传递给JVM。它将在标准输出上打印关于SSL连接和握手的详细信息。
我也试过这个解决方案(http://nelenkov.blogspot.ch/2011/12/using-custom-certificate-trust-store-on.html),但仍然是相同的消息...是否有可能服务器配置不好? – TheOnlyYam
嘿,这是相当长的一段时间,但你找到了解决方案吗?我也有同样的问题。我有一个pem和一个p12文件。 – Wicked161089