7

我知道这个主题在很多地方都被讨论过,但是在我经历了几乎所有这些之后,我决定创建我的第一个 StackOverflow 问题......

问题如下:

我想连接到使用证书来限制访问的安全 Web 服务 (https),​​并使用用户名/密码对用户进行身份验证。所以我有一个客户端证书(p12 文件)和一个服务器证书(pem 或 der 文件)。我尝试使用 HttpURLConnection 类,因为据我所知,Android 将不再支持 Apache 库。

所以这是我的实现(serverCert 和 clientCert 是我的文件的完整路径):

        // Load CAs from our reference to the file
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        InputStream caInput = new BufferedInputStream(new FileInputStream(serverCert));
        X509Certificate serverCertificate;

        try {
            serverCertificate = (X509Certificate)cf.generateCertificate(caInput);
            System.out.println("ca=" + serverCertificate.getSubjectDN());
        } finally {
            caInput.close();
        }
        Log.d(TAG, "Server Cert: " + serverCertificate);

        // Create a KeyStore containing our trusted CAs
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null);
        trustStore.setCertificateEntry("my ca", serverCertificate);

        //Load the Client certificate in the keystore
        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        FileInputStream fis = new FileInputStream(clientCert);
        keyStore.load(fis,CLIENT_PASSWORD);

        // Create a TrustManager that trusts the CAs in our KeyStore
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(trustStore);

        //Build the SSL Context
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmf.init(keyStore, pref.getString(Constants.clientCertificatePassword, "").toCharArray

());


    //Create the SSL context
                SSLContext sslContext = SSLContext.getInstance("TLS");
                sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
...
    //And later, we use that sslContext to initiatize the socketFactory

                urlConnection = (HttpsURLConnection) requestedUrl.openConnection();
         urlConnection.setSSLSocketFactory(CertificateManager.getInstance().getSslContext().getSocketFactory());
...

所以我可以创建我的 SSLContext,并显示我的两个证书内容。但是当我尝试执行 HTTPS 连接时,出现以下异常:

09-23 13:43:30.283: W/System.err(19422): javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: 找不到证书路径的信任锚。

你们中有人遇到过以下错误吗?你的解决方案是什么?

这些是我浏览的网站(没有成功):

http://blog.chariotsolutions.com/2013/01/https-with-client-certificates-on.html

http://nelenkov.blogspot.ch/2011/12/using-custom-certificate-trust-store-on.html

4

1 回答 1

1

在您的代码中,您正在创建和初始化 aSSLContext但不使用它。也许你应该更换:

urlConnection.setSSLSocketFactory(CertificateManager.getInstance().getSslContext().getSocketFactory());

经过

urlConnection.setSSLSocketFactory(sslContext.getSocketFactory());

如果可能,我还建议您将选项传递-Djavax.net.debug=all给 JVM。它将在标准输出上打印有关 SSL 连接和握手的详细信息。

于 2013-10-12T19:48:53.697 回答