如何在TrustManager中使用CertificateException



我把我的应用程序上传到了play商店,我收到了谷歌开发者的一封电子邮件,说我必须修改https代码中的句子。我正在使用TrustManager功能通过https提交数据。我的url中有一个有效的ssl证书,一切都很正常。但我有一个修改并向代码添加CertificateException的截止日期。

谷歌发送给我:

TrustManager

你可以在谷歌帮助中心的这篇文章中找到更多关于TrustManager的信息。

主机名验证程序

您的应用程序正在使用HostnameVerifier接口的不安全实现。你可以在谷歌帮助中心的这篇文章中找到更多关于如何解决这个问题的信息。

这是我的代码:

public class HttpsTrustManager implements X509TrustManager{
private static TrustManager[] trustManagers;
private static final X509Certificate[] _AcceptedIssuers = new X509Certificate[]{};
private X509Certificate[] x509Certificates;
@Override
public void checkClientTrusted(
java.security.cert.X509Certificate[] x509Certificates, String s)
throws CertificateException {
}
@Override
public void checkServerTrusted(
java.security.cert.X509Certificate[] x509Certificates, String s)
throws CertificateException {
}
public boolean isClientTrusted(X509Certificate[] chain) {
return true;
}
public boolean isServerTrusted(X509Certificate[] chain) {
return true;
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return _AcceptedIssuers;
}
public static void allowAllSSL() {
HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String arg0, SSLSession arg1) {
return true;
}
});
SSLContext context = null;
if (trustManagers == null) {
trustManagers = new TrustManager[]{new HttpsTrustManager()};
}
try {
context = SSLContext.getInstance("TLS");
context.init(null, trustManagers, new SecureRandom());
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
}
HttpsURLConnection.setDefaultSSLSocketFactory(context
.getSocketFactory());
}
}

我希望你能帮助我。谢谢。

在你的代码中,你只是信任一切。这是不安全的。正如谷歌所说,你应该判断证书并提出一个异常。像这样,

@Overridepublic void checkServer受信任(java.security.cert.X509Certificate[]x509Certificates,字符串s(throws CertificateException{

// do some check here if the x509Certificates not valid just raise an CertificateException exception.
// this will check the certificate          
if(!checkTheHostName(x509Certificates[0]){
throw new CertificateException("the certificate is invalid ...");
}
}

private boolean checkTheHostName(Certificate certificate,String hostName){
return OkHostnameVerifier.INSTANCE.verify("www.yourhostname.com",certificate)
}
the OkHostnameVerifier's code, just in 
https://android.googlesource.com/platform/external/okhttp/+/e82a796/src/main/java/com/squareup/okhttp/internal/tls/OkHostnameVerifier.java

和代码

@Override
public boolean verify(String hostName, SSLSession session) {
// here you should check the hostName, through session
// do not just return true here, cause it's not safe. like man-in-middle-attack
Certificate[] certificates = session.getPeerCertificates();
return verify(host, (X509Certificate) certificates[0]);

}

相关内容

  • 没有找到相关文章

最新更新