如何在Android应用中修复X509TrustManager的不安全实现

Nab*_*eel 20 android-security trustmanager

谷歌已经建议我在我的Android应用程序中有一个不安全的接口X509TrustManager实现,需要更改我的代码如下:

要正确处理SSL证书验证,请在自定义X509TrustManager接口的checkServerTrusted方法中更改代码,以便在服务器提供的证书不符合您的期望时引发CertificateException或IllegalArgumentException.对于技术问题,您可以发布到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);
}
Run Code Online (Sandbox Code Playgroud)

Nab*_*eel 23

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

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

  • 如果CA是自签名CA,则此解决方案不是一个好主意!有时候我们必须接受自签名的CA. (3认同)
  • 不要使用这个非常糟糕的代码!该代码允许中间人攻击,并使整个SSL点无效.`checkValidity()`方法只检查证书是否未过期而没有其他内容,这意味着即使证书是针对另一台服务器而且没有任何签名,此代码也会很乐意接受任何未过期的证书. (3认同)