即使使用CA签名的证书,证书固定也会失败

时间:2017-07-27 14:00:51

标签: android retrofit okhttp certificate-pinning

我正在尝试使用Retrofit在Android上使用证书固定功能。我正在尝试评估有效的Verisign签名证书。

我收到以下错误:

  

HTTP FAILED:javax.net.ssl.SSLPeerUnverifiedException:无法找到签署证书的受信任证书。

为什么证书引脚不能评估设备的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();

1 个答案:

答案 0 :(得分:1)

找到答案。我可以获得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();

}