Android Volley Self签名证书

时间:2017-04-06 07:01:57

标签: https certificate android-volley

我试图从我的Android应用程序访问HTTPS网址。 我的服务器端有自签名证书(server_certificate.cer)。

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

并获取javax.net.ssl.SSLHandshakeException:java.security.cert.CertPathValidatorException:未找到证书路径的信任锚。

1 个答案:

答案 0 :(得分:0)

我成功地遵循了该教程。

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

我发现最简单的方法是将PKCS12格式用于密钥库文件。 (使用-deststoretype PKCS12转换密钥库时添加keytool param)

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

我必须将HttpsURLConnection.setDefaultHostnameVerifier()添加到自定义HostnameVerifier并将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);
    }
}