不受信任的SSL证书 - 自定义密钥库问题

时间:2014-08-05 19:04:35

标签: android ssl

我的Web服务器有自己的PKI基础架构,带有CA和中间CA.然后我有一个由中间CA签名的Web证书,我希望我的应用程序与服务器通信。根据{{​​3}},解决方案是创建自己的密钥库。所以我将根CA证书与应用程序捆绑在一起,并试图查看是否可行。它没有,我得到以下错误:

javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.

所以我的问题是这个。由于SSL证书是由我的中间CA签署的,我应该将证书导入自定义密钥库,还是我需要两者,或者这里有其他错误吗?

最终,由不受Android信任的CA签署的SSL证书,这是正确的方法吗?

谢谢!

以下是设置密钥库管理器的代码。

public SSLContext getTrusted() throws Exception{
        // Load CAs from an InputStream
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        AssetManager assManager = context.getAssets();
        InputStream is = null;
        try {
                is = assManager.open("ca.cert.crt");
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        InputStream caInput = new BufferedInputStream(is);

        Certificate ca;
        try {
            ca = cf.generateCertificate(caInput);
            Log.d("TrustMan", "ca=" + ((X509Certificate) ca).getSubjectDN());
        } finally {
            caInput.close();
        }

        // Create a KeyStore containing our trusted CAs
        String keyStoreType = KeyStore.getDefaultType();
        KeyStore keyStore = KeyStore.getInstance(keyStoreType);
        keyStore.load(null, null);
        keyStore.setCertificateEntry("ca", ca);


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

        // Create an SSLContext that uses our TrustManager
        SSLContext context = SSLContext.getInstance("TLS");
        context.init(null, tmf.getTrustManagers(), null);

        return context;
    }

然后我尝试按如下方式使用它。

HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
TrustMan tm = new TrustMan(context);
SSLContext sslContext;
sslContext = tm.getTrusted();

connection.setSSLSocketFactory(sslContext.getSocketFactory());

1 个答案:

答案 0 :(得分:1)

代码确实有效,但是当我从我的类中返回SSLContext时却没有。我调整了类来返回TrustManagerFactory,使用中间CA证书现在工作正常!

谢谢!