【问题标题】:Android Volley Self signed certificateAndroid Volley 自签名证书
【发布时间】:2017-09-01 01:22:48
【问题描述】:

我正在尝试从我的 android 应用程序访问 HTTPS url。 我的服务器端有自签名证书(server_certificate.cer)。

我想知道如何将自签名证书添加到 volley 网络请求以信任我的自签名证书。 尝试使用http://blog.applegrew.com/2015/04/using-pinned-self-signed-ssl-certificate-with-android-volley/

并得到 javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certificate path not found.

【问题讨论】:

    标签: https certificate android-volley


    【解决方案1】:

    我成功地遵循了该教程。

    您需要创建一个密钥库文件(例如“cert_keystore.pkcs12”)来包含您的服务器证书并将其添加到您的应用中。

    我发现对密钥库文件使用 PKCS12 格式是最简单的。 (使用keytool转换密钥库时添加-deststoretype PKCS12参数)

    我的测试服务器位于 IP 地址上,我必须禁用主机名验证才能使用我的自签名证书。这个other tutorial 很有用。

    我必须将带有自定义 HostnameVerifier 的 HttpsURLConnection.setDefaultHostnameVerifier() 和 HttpsURLConnection.setDefaultSSLSocketFactory () 添加到 newSslSocketFactory()。

    (Volley.newRequestQueue(mCtx.getApplicationContext(), new HurlStack(null, newSslSocketFactory())中使用newSslSocketFactory())

    新的 newSslSocketFactory() 函数现在是:

    private SSLSocketFactory newSslSocketFactory()
    {
        try
        {
            KeyStore trusted = KeyStore.getInstance ("PKCS12");
    
            // Get the raw resource, which contains the keystore with
            // your trusted certificates (root and any intermediate certs)
            InputStream in = mCtx.getApplicationContext().getAssets ().open ("cert_keystore.pkcs12");
            try {
                // Initialize the keystore with the provided trusted certificates
                // Provide the password of the keystore
                trusted.load (in, "password".toCharArray ());
            } finally {
                in.close();
            }
    
            String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
            TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
            tmf.init(trusted);
    
    
            HostnameVerifier hostnameVerifier = new HostnameVerifier() {
                @Override
                public boolean verify (String hostname, SSLSession session) {
    
                    return hostname.equals ("192.168.1.10"); //The Hostname of your server
    
                }
            };
    
    
            HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
    
    
            SSLContext context = SSLContext.getInstance("TLS");
            context.init(null, tmf.getTrustManagers(), null);
    
            SSLSocketFactory sf = context.getSocketFactory();
            HttpsURLConnection.setDefaultSSLSocketFactory (sf);
    
            return sf;
        }
        catch (Exception e)
        {
            throw new AssertionError(e);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2014-12-12
      • 1970-01-01
      • 2015-11-16
      • 1970-01-01
      • 2021-09-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-30
      相关资源
      最近更新 更多