android - Android 中不安全的 HostnameVerifier

标签 android ssl-certificate hostname android-security trustmanager

3 月 1 日之后,当我将我的应用程序上传到测试组时,我收到了来自 Google 的特定邮件,其中引用了:

This information is intended for developers with app(s) using an unsafe implementation of the HostnameVerifier interface, which accepts all hostnames when establishing an HTTPS connection to a remote host with the setDefaultHostnameVerifier API

在网上搜索后,我找到了一些链接,但大多数链接都建议使用第三方库,但在我的整个应用程序中,我已经为 restcalls 完成了简单的 HTTPS 请求。我用于休息调用的代码是:

TrustManager[] trustAllCerts = new TrustManager[] {
    new X509TrustManager() {

        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        public void checkClientTrusted(X509Certificate[] certs, String authType) {}
        public void checkServerTrusted(X509Certificate[] certs, String authType) {}
    }
};

// Install the all-trusting trust manager
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

// Create all-trusting host name verifier
HostnameVerifier hostnameVerifier = new HostnameVerifier() {
    @Override
    public boolean verify(String hostname, SSLSession session) {
        HostnameVerifier hv =
        HttpsURLConnection.getDefaultHostnameVerifier();
        return hv.verify("something.com", session);
    }
};

URL url = new URL("Something");
urlConnection = (HttpsURLConnection) url.openConnection();
urlConnection.setHostnameVerifier(hostnameVerifier);

有谁知道可以编写什么类型的代码来从 Google 的警告中恢复。但我不想使用像 Volley 这样的第三方库。

最佳答案

我认为您正在通过 URL 检索数据或将数据发布到服务器。 如果您想使用相同的方法(Trust Manager)回答问题,请点击此链接:- TrustManagerVulnerabilitySolution (或者) 我使用了另一种方法来克服这个问题。如果您想尝试另一种方法,请按照以下步骤操作:-

  1. 通过 Web 浏览器下载 URL 的 SSL 证书。

  2. 在目录-> res/xml/network_security_config.xml 中创建一个network_security_config.xml

  3. 将这些代码添加到 Xml 文件中:- `

    <network-security-config>
            <domain-config>
                <domain includeSubdomains="true">example.com</domain>
                <trust-anchors>
                    <certificates src="@raw/my_ca"/>
                </trust-anchors>
            </domain-config>
        </network-security-config>`
    
  4. 将您下载的 SSL 证书放在名为“my_ca”的目录中-> res/raw/'my_ca'

  5. 将此添加到您的 list 中:- <application android:networkSecurityConfig="@xml/network_security_config">

  6. 就是这样。有关详细信息,请参阅:- Networksecurityconfiguration

关于android - Android 中不安全的 HostnameVerifier,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42641372/

相关文章:

python - django:使用 NGINX 的 SECURE_SSL_REDIRECT 应用程序崩溃

php - 为 LDAPS 连接验证自签名证书

python - 无法解析 pi 的主机名

python - 基于 IP 或主机名的 Django 设置

java - Android 服务需要在后台运行,直到应用程序被杀死

android - 是否可以与 Android 上的 Secure Element Applet 通信?

java - Spring Boot - 带有自签名证书的客户端服务器 REST API

java - 跨平台收集当前服务器信息

Android listview 滚动到底部以从 sqlite 加载更多数据

java - 适配器中的空指针异常