【发布时间】:2016-06-03 13:20:34
【问题描述】:
我的 Android 应用程序应该能够与任何启用 SSL 的服务器通信。由于我的应用程序是演示应用程序,并且我的客户在登录时在应用程序中添加了他们自己的 SSL 服务器详细信息,所以我不知道我需要验证哪个 SSL 证书。
以下是我之前的代码。
public SSLSocketFactory getSSLSocketFactory(String hostname) {
try {
HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, new X509TrustManager[] { new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
} }, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
} catch (Exception e) {
e.printStackTrace();
}
return HttpsURLConnection.getDefaultSSLSocketFactory();
}
当我更新到 Playstore 时,它被拒绝了,原因如下
要正确处理 SSL 证书验证,请更改自定义 X509TrustManager 接口的 checkServerTrusted 方法中的代码,以在服务器提供的证书不符合您的期望时引发 CertificateException 或 IllegalArgumentException。对于技术问题,您可以发布到 Stack Overflow 并使用标签“android-security”和“TrustManager”。
我想更新类似这样的代码
public static HttpClient wrapClient(HttpClient base) {
try {
SSLContext ctx = SSLContext.getInstance("TLS");
X509TrustManager tm = new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException { }
public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException { }
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
ctx.init(null, new TrustManager[]{tm}, null);
SSLSocketFactory ssf = new SSLSocketFactory(ctx);
ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
ClientConnectionManager ccm = base.getConnectionManager();
SchemeRegistry sr = ccm.getSchemeRegistry();
sr.register(new Scheme("https", ssf, 443));
return new DefaultHttpClient(ccm, base.getParams());
} catch (Exception ex) {
return null;
}
}
Playstore 接受这个吗?有没有更好的处理方法?
提前致谢。
【问题讨论】:
标签: android ssl https google-play x509certificate