我的应用程序需要连接到我自己的服务器,所以我将我的服务器的自签名证书添加到KeyStore。它适用于我的服务器,但问题是,现在我的应用程序不会接受所有其他证书!例如,如果我尝试连接到https://maps.googleapis.com/,我会得到一个丢失的证书异常。我怎么能解决这个问题?信任自签名证书时的Android应用程序SSL问题
这里是我信任我的证书:
public static void setSelfSignedCertSSLContext(AssetManager assets)
throws Exception {
// Load self-signed cert from an InputStream
CertificateFactory cf = CertificateFactory.getInstance("X.509");
InputStream caInput = assets.open("selfSigned.cer");
Certificate ca;
try {
ca = cf.generateCertificate(caInput);
Log.d(LOG_TAG, "ca=" + ((X509Certificate) ca).getSubjectDN());
} finally {
caInput.close();
}
// Create a KeyStore containing our trusted CAs
String keyStoreType = KeyStore.getDefaultType();
KeyStore keyStore = KeyStore.getInstance(keyStoreType);
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);
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory
.getDefaultAlgorithm());
kmf.init(keyStore, "changeit".toCharArray());
// Create an SSLContext that uses our TrustManager
SSLContext context = SSLContext.getInstance("TLS");
SSLContext.setDefault(context);
context.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
HttpsURLConnection.setDefaultSSLSocketFactory(context
.getSocketFactory());
HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
public boolean verify(String string, SSLSession ssls) {
return true;
}
});
Log.d(LOG_TAG, "SSLContext set successfully");
}
,这里是异常试图连接到谷歌时,我得到:
06-29 23:27:59.181: E/AdapterClass(16358): javax.net.ssl.SSLHandshakeException:
java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
重复的https://stackoverflow.com/questions/24429485/loading-self-signed-cert-to-httpsurlconnection-breaks-default-ca-cert-validation/24430187 – CommonsWare