Google建议我在Android应用程序中有一个不安全的X509TrustManager接口实现,需要更改代码如下:
若要正确处理SSL证书验证,请更改自定义X509TrustManager接口的checkServerTrusted方法中的代码,以便在服务器提供的证书不符合预期时引发CertificateException或IllegalArgumentException。对于技术问题,您可以post to Stack Overflow并使用标记“Android-Security”和“TrustManager”。
public EasySSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
super(truststore);
TrustManager tm = new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
mContext.init(null, new TrustManager[] { tm }, null);
}
我使用以下代码解决了这个问题:
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
try {
chain[0].checkValidity();
} catch (Exception e) {
throw new CertificateException("Certificate not valid or trusted.");
}
}