2017-07-27 97 views
0

我正嘗試使用Android上的證書鎖定進行修改。我正在評估一個有效的Verisign簽名證書。即使使用CA簽名證書,證書鎖定也會失敗

我得到以下錯誤:

HTTP FAILED: javax.net.ssl.SSLPeerUnverifiedException: Failed to find a trusted cert that signed Certificate.

爲什麼不能證書平納不評估對設備的CA根證書?它是否無法訪問設備信任?或者,設備信任可能不包含整個證書鏈。但是爲什麼我的SSL通信不會失敗?

// Pin Certificate 
CertificatePinner certificatePinner = new CertificatePinner.Builder() 
     .add("www.mydomain.com", "sha256/somerandompublickeystring") 
     .build(); 

// To handle self-signed cert 
OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder(); 

OkHttpClient client = clientBuilder.connectTimeout(120, TimeUnit.SECONDS) 
     .writeTimeout(120, TimeUnit.SECONDS) 
     .readTimeout(120, TimeUnit.SECONDS) 
     .certificatePinner(certificatePinner) 
     .build(); 

回答

0

找到了答案。我可以如下所示獲得Root信任,並在sslSocketFactory調用中使用它。這對我有效。

OkHttpClient client = clientBuilder.connectTimeout(120, TimeUnit.SECONDS) 
     .writeTimeout(120, TimeUnit.SECONDS) 
     .readTimeout(120, TimeUnit.SECONDS) 
     .sslSocketFactory(getSystemDefaultSSLSocketFactory(app)) 
     .certificatePinner(certificatePinner) 
     .build(); 

private static SSLSocketFactory getSystemDefaultSSLSocketFactory(Application app) { 
    SSLContext sslContext = null; 
    try 
    { 
     TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(
       TrustManagerFactory.getDefaultAlgorithm()); 
     trustManagerFactory.init((KeyStore) null); 
     TrustManager[] trustManagers = trustManagerFactory.getTrustManagers(); 
     if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) { 
      throw new IllegalStateException("Unexpected default trust managers:" + Arrays.toString(trustManagers)); 
     } 
     sslContext = SSLContext.getInstance("TLS"); 
     sslContext.init(null, trustManagers, null); 

    } 
    catch(Exception ex) 
    { 
     Log.e("TAG",ex.getMessage()); 
    } 
    return sslContext.getSocketFactory(); 

}

+0

考慮給OkHttp兩個證書平納和信任管理器。否則,OkHttp需要用反射來查找信任管理器,而且速度較慢。 –