如何修复Android应用中X509TrustManager的不安全实现 [英] How to fix unsafe implementation of X509TrustManager in Android app

查看:227
本文介绍了如何修复Android应用中X509TrustManager的不安全实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Google建议我在Android应用程序中实现X509TrustManager接口的不安全实现,并且需要按以下方式更改代码:

Google has advised that I have an unsafe implementation of the interface X509TrustManager in my Android application and need to change my code as follows:

要正确处理SSL证书验证,请在 您的自定义X509TrustManager接口的checkServerTrusted方法 每次引发CertificateException或IllegalArgumentException 服务器提供的证书不符合您的要求 期望.如有技术问题,您可以发布到Stack Overflow 并使用标签"android-security"和"TrustManager".

To properly handle SSL certificate validation, change your code in the checkServerTrusted method of your custom X509TrustManager interface to raise either CertificateException or IllegalArgumentException whenever the certificate presented by the server does not meet your expectations. For technical questions, you can post to Stack Overflow and use the tags "android-security" and "TrustManager."

如何修改以下代码以解决上述问题?

How can the following code be modified to fix the above issue?

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);
}

推荐答案

我已经使用以下代码解决了这个问题:

I have solved this using the following code:

public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                try {
                    chain[0].checkValidity();
                } catch (Exception e) {
                    throw new CertificateException("Certificate not valid or trusted.");
                }
            }

这篇关于如何修复Android应用中X509TrustManager的不安全实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆