无法在Android中使用自签名证书

时间:2016-10-11 13:55:09

标签: android ssl iis https ssl-certificate

它会抛出如下所示的异常

javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.

此Android程序连接到部署在IIS上的ASP.NET MVC,我使用OpenSSL创建CA的.csr ,. key,.crt文件和我的服务器证书。 然后我将服务器证书的.crt文件转换为.pfx格式并将其导入IIS。

我在Android Developer找到了解决方案。但我的代码与它列出的代码类似。

 CertificateFactory cf = CertificateFactory.getInstance("X.509","BC");

 InputStream caInput = getResources().openRawResource(R.raw.root);  //here "R.raw.root" is a .bks file converted from my CA's .crt file , and a .bks file converted from my server's .crt file , but both throw this exception
 Certificate ca;
 try
{
     ca = cf.generateCertificate(caInput);

} finally

{
      caInput.close();
}

// Create a KeyStore containing our trusted CAs
//String keyStoreType = KeyStore.getDefaultType();
KeyStore keyStore = KeyStore.getInstance("BKS");
keyStore.load(null, null);
keyStore.setCertificateEntry("ca", ca);

// Create a TrustManager that trusts the CAs in our KeyStore
String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
tmf.init(keyStore);

// Create an SSLContext that uses our TrustManager
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, tmf.getTrustManagers(),null);

// Tell the URLConnection to use a SocketFactory from our SSLContext
URL url = new URL("https://172.18.13.178:63123/Home/Test");
HttpsURLConnection urlConnection =(HttpsURLConnection) url.openConnection();
urlConnection.setSSLSocketFactory(context.getSocketFactory());
InputStream in = urlConnection.getInputStream();

//omit other code
}

Android Developer说这是这个错误的解决方案,但我写的代码与它类似,但它失败了。

所以有人告诉我问题出在哪里? Android Develop提供的方式不起作用。

0 个答案:

没有答案