SSLHandshakeException Trust anchor for certification path not found Android HTTPS

后端 未结 2 1527
挽巷
挽巷 2020-12-02 15:07

I\'m trying to establish a connection to a HTTPS site and I got this exception: javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Tru

相关标签:
2条回答
  • 2020-12-02 15:19

    Updates:

    • I've never been an expert at this matter, the following is only a workaround and might not be secure, use it at your own risk
    • This post is 3+ years old, so it may be outdated by now (code will not compile) but you should find be able to find the updated approach or official docs saying certain parts are deprecated or removed

    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());  
    

    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

    0 讨论(0)
  • 2020-12-02 15:20

    in my case i was running my server on Https on local host i have to switch to http and it worked maybe the ssl certificate of the server is not trusted by the android device

    0 讨论(0)
提交回复
热议问题