带有客户端证书(crt,p12)的OkHttp:java.security.cert.CertPathValidatorException:找不到证书路径的信任锚

时间:2019-05-23 09:39:54

标签: java android kotlin retrofit okhttp

我正在尝试使用OKHttp和Retrofit 2发出请求。此请求应通过发送证书(必须为p12或crt)来完成。我们尝试了不同的方法,但是没有人能让我成功。我正在使用badssl.com进行测试,它使我可以使用以下证书向以下网址提出请求:https://client.badssl.com,您可以在这里找到证书:https://badssl.com/download/

我试图将p12和crt包括在项目的资产文件夹和原始文件夹中,并创建密钥库,SSLSocketFactory和TrustManager。 由于此操作无效,因此我也尝试创建一个可以发出任何请求的不安全的OkHttpClient,但未成功。 在这两种情况下,我都有: “ javax.net.ssl.SSLHandshakeException:java.security.cert.CertPathValidatorException:找不到证书路径的信任锚”

public static SSLContext getSSLConfig(Context context) throws CertificateException, IOException,
            KeyStoreException, NoSuchAlgorithmException, KeyManagementException {

        // Loading CAs from an InputStream
        CertificateFactory cf = null;
        cf = CertificateFactory.getInstance("X.509");

        Certificate ca;
        // I'm using Java7. If you used Java6 close it manually with finally.
        try (InputStream cert = context.getResources().openRawResource(R.raw.somecert)) {
            ca = cf.generateCertificate(cert);
        }

        // Creating a KeyStore containing our trusted CAs
        String keyStoreType = KeyStore.getDefaultType();
        KeyStore keyStore = KeyStore.getInstance(keyStoreType);
        keyStore.load(null, null);
        keyStore.setCertificateEntry("ca", ca);

        // Creating a TrustManager that trusts the CAs in our KeyStore.
        String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
        tmf.init(keyStore);

        // Creating an SSLSocketFactory that uses our TrustManager
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, tmf.getTrustManagers(), null);

        return sslContext;
    }
val client: OkHttpClient = OkHttpClient.Builder()
            .sslSocketFactory(SSLConfigUtils.getSSLConfig(MyClass.getContext()).socketFactory)
            .hostnameVerifier { _, _ -> true }
            .build()

            val retrofit = Retrofit.Builder()
                .addCallAdapterFactory(
                    RxJava2CallAdapterFactory.create())
                .addConverterFactory(
                    GsonConverterFactory.create(gson))
                .baseUrl("https://client.badssl.com/")
                .client(client)
                .build()

我希望正确提出翻新请求,但每个请求都会向我返回此错误:

    javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
        at com.google.android.gms.org.conscrypt.ConscryptFileDescriptorSocket.startHandshake(:com.google.android.gms@17122040@17.1.22 (100700-245988633):43)
        at okhttp3.internal.connection.RealConnection.connectTls(RealConnection.java:319)
        at okhttp3.internal.connection.RealConnection.establishProtocol(RealConnection.java:283)
        at okhttp3.internal.connection.RealConnection.connect(RealConnection.java:168)
        at okhttp3.internal.connection.StreamAllocation.findConnection(StreamAllocation.java:257)
        at okhttp3.internal.connection.StreamAllocation.findHealthyConnection(StreamAllocation.java:135)
        at okhttp3.internal.connection.StreamAllocation.newStream(StreamAllocation.java:114)
        at okhttp3.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.java:42)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
        at okhttp3.internal.cache.CacheInterceptor.intercept(CacheInterceptor.java:93)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
        at okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.java:93)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
        at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.java:126)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
        at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:254)
        at okhttp3.RealCall.execute(RealCall.java:92)
        at retrofit2.OkHttpCall.execute(OkHttpCall.java:186)
        at retrofit2.adapter.rxjava2.CallExecuteObservable.subscribeActual(CallExecuteObservable.java:41)
        at io.reactivex.Observable.subscribe(Observable.java:12267)
        at retrofit2.adapter.rxjava2.BodyObservable.subscribeActual(BodyObservable.java:34)
        at io.reactivex.Observable.subscribe(Observable.java:12267)
        at io.reactivex.internal.operators.observable.ObservableSubscribeOn$SubscribeTask.run(ObservableSubscribeOn.java:96)
        at io.reactivex.Scheduler$DisposeTask.run(Scheduler.java:578)
        at io.reactivex.internal.schedulers.ScheduledRunnable.run(ScheduledRunnable.java:66)
        at io.reactivex.internal.schedulers.ScheduledRunnable.call(ScheduledRunnable.java:57)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:301)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
        at java.lang.Thread.run(Thread.java:919)
     Caused by: java.security.cert.CertificateException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
        at com.android.org.conscrypt.TrustManagerImpl.checkTrustedRecursive(TrustManagerImpl.java:656)
        at com.android.org.conscrypt.TrustManagerImpl.checkTrustedRecursive(TrustManagerImpl.java:615)
        at com.android.org.conscrypt.TrustManagerImpl.checkTrusted(TrustManagerImpl.java:505)
        at com.android.org.conscrypt.TrustManagerImpl.checkTrusted(TrustManagerImpl.java:424)
        at com.android.org.conscrypt.TrustManagerImpl.getTrustedChainForServer(TrustManagerImpl.java:352)
        at android.security.net.config.NetworkSecurityTrustManager.checkServerTrusted(NetworkSecurityTrustManager.java:94)
        at android.security.net.config.RootTrustManager.checkServerTrusted(RootTrustManager.java:89)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.google.android.gms.org.conscrypt.Platform.checkTrusted(:com.google.android.gms@17122040@17.1.22 (100700-245988633):2)
2019-05-23 11:37:15.389 5640-5640/it.sogetel.agtcs E/Errore:     at com.google.android.gms.org.conscrypt.Platform.checkServerTrusted(:com.google.android.gms@17122040@17.1.22 (100700-245988633):1)
        at com.google.android.gms.org.conscrypt.ConscryptFileDescriptorSocket.verifyCertificateChain(:com.google.android.gms@17122040@17.1.22 (100700-245988633):12)
        at com.google.android.gms.org.conscrypt.NativeCrypto.SSL_do_handshake(Native Method)
        at com.google.android.gms.org.conscrypt.NativeSsl.doHandshake(:com.google.android.gms@17122040@17.1.22 (100700-245988633):7)
        at com.google.android.gms.org.conscrypt.ConscryptFileDescriptorSocket.startHandshake(:com.google.android.gms@17122040@17.1.22 (100700-245988633):14)
            ... 33 more
     Caused by: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
            ... 47 more

1 个答案:

答案 0 :(得分:0)

OkHttp中有一个test case,用于配置客户端身份验证。尽管您应该注意,它可能会在内存中生成证书,而不是从文件中加载证书,但这可能需要一个有用的示例。

相关代码在okhttp-tls模块中。

还请注意,您的TrustManager必须包含服务器的证书,或包含对其进行签名的证书颁发机构根证书之一。