且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

SSLHandshakeException 未找到证书路径的信任锚 Android HTTPS

更新时间:2021-09-07 21:48:30

更新:

  • 我从来不是这方面的专家,以下只是一种解决方法,可能不安全,使用时风险自负
  • 这篇文章已有 3 年以上的历史,所以它现在可能已经过时(代码无法编译),但您应该能够找到更新的方法或官方文档,说明某些部分已弃用或删除

感谢 noloader 给我指正方向.我使用以下方法解决了我的问题:

Thank noloader for pointing me in the correction direction. I solved my issue using the following:

String keyStoreType = KeyStore.getDefaultType();
            KeyStore keyStore = KeyStore.getInstance(keyStoreType);
            keyStore.load(null, null);
            keyStore.setCertificateEntry("ca", ca);// my question shows how to get 'ca'
TrustManagerFactory tmf = TrustManagerFactory.getInstance(
    TrustManagerFactory.getDefaultAlgorithm());
// Initialise the TMF as you normally would, for example:
tmf.init(ca); 

TrustManager[] trustManagers = tmf.getTrustManagers();
final X509TrustManager origTrustmanager = (X509TrustManager)trustManagers[0];

TrustManager[] wrappedTrustManagers = new TrustManager[]{
   new X509TrustManager() {
       public java.security.cert.X509Certificate[] getAcceptedIssuers() {
          return origTrustmanager.getAcceptedIssuers();
       }

       public void checkClientTrusted(X509Certificate[] certs, String authType) {
           origTrustmanager.checkClientTrusted(certs, authType);
       }

       public void checkServerTrusted(X509Certificate[] certs, String authType) {
           try {
               origTrustmanager.checkServerTrusted(certs, authType);
           } catch (CertificateExpiredException e) {
               // Do what you need to do, log to Crashlytics?
           }
       }
   }
};

SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, wrappedTrustManagers, null);
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());  

在我的问题中提到的为该站点找到的 3 个证书中,对我有用的是VeriSign Class 3 Secure Server CA - G3

Out of the 3 certificates found for the site, mentioned in my question, the one that worked for me was the VeriSign Class 3 Secure Server CA - G3