我的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();
}
当我更新我的应用到Play Store时,它被拒绝了,原因如下:
为了正确处理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是否接受这个?有没有更好的处理方法?
提前感谢。