将证书添加到自定义密钥库后,信任锚未找到证书路径错误

时间:2017-06-02 14:11:18

标签: android ssl

我正在尝试使用HttpsUrlConnection来访问安全的Web服务。

我用过

 private SSLSocketFactory getSSLSocketFactory() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException, CertificateException, IOException, UnrecoverableKeyException {


    CertificateFactory cf = CertificateFactory.getInstance("X.509");

    InputStream caInput = new BufferedInputStream(getAssets().open("xxxx.cer"));
    X509Certificate ca = null;
    try {
        ca = (X509Certificate)cf.generateCertificate(caInput);

        Log.v("TAG","ca = "+ca);

    } 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);
    String clientCertPassword = "xxxx!";

    KeyManagerFactory kmf = KeyManagerFactory.getInstance("X509");
    kmf.init(keyStore, clientCertPassword.toCharArray());









    KeyStore trustStore = KeyStore.getInstance("PKCS12");
    InputStream caInput2 = new BufferedInputStream(getAssets().open("xxxx.pfx"));
    trustStore.load(caInput2, clientCertPassword.toCharArray());


    TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(trustStore);



    KeyManager[] keyManagers = kmf.getKeyManagers();
    SSLContext sslContext = SSLContext.getInstance("SSL");



    TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();

    X509TrustManager xtm = (X509TrustManager) trustManagers[0];

    for (X509Certificate cert : xtm.getAcceptedIssuers()) {
        String certStr = "S:" + cert.getSubjectDN().getName() + "\nI:"
                + cert.getIssuerDN().getName();

        Log.d("TAG", certStr);
    }



    sslContext.init(keyManagers,trustManagers,null);



    return sslContext.getSocketFactory();


}

所以上面这个方法可以用来设置SSLSocketFactory进行连接。

但即使将证书添加到我的自定义信任管理器,我仍然收到错误

java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.

我现在还没有任何线索。有人可以提供一些建议吗?

我现在也注意到了一件事......我使用的证书不是来自有效的CA.

非常感谢。

0 个答案:

没有答案