javax.net.ssl.SSLHandshakeException: доверенная привязка для пути сертификации не найдена - PullRequest
0 голосов
/ 19 декабря 2018

Я получаю эту ошибку

D/OkHttp: <-- HTTP FAILED: javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.

Я использую Android SDK версии 4.2.2, в то время как мой код работает нормально с Android SDK версии 8.

code

    public static Retrofit getClient() {

    if (retrofit == null) {
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        Log.d("testing", "0000000");
        OkHttpClient.Builder okHttpClient = new OkHttpClient().newBuilder().addInterceptor(loggingInterceptor);
        okHttpClient = enableTls12OnPreLollipop(okHttpClient);


        final String authUserName = "@@@@@-###-***";
        final String authPassword = "*****";

        if (authUserName != null && authPassword != null) { // set authentication header if credentials available for accessing endpoints

            okHttpClient.addInterceptor(new Interceptor() {
                @Override
                public okhttp3.Response intercept(Chain chain) throws IOException {
                    String credentials = authUserName + ":" + authPassword;
                    final String basic = Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);
                    RequestBody body = RequestBody.create(MediaType.parse("application/x-www-form-urlencoded"), "grant_type=client_credentials");
                    Request newRequest = chain.request().newBuilder().addHeader(HTTP_AUTH_HEADER, "Basic  " + basic).addHeader("Content_Type", "application/x-www-form-urlencoded").post(body).build();
                    return chain.proceed(newRequest);

                }
            });
        }
        retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .client(okHttpClient.build())
                .build();
    }
    return retrofit;
}

public static OkHttpClient.Builder enableTls12OnPreLollipop(OkHttpClient.Builder client) {


    Context context = null;

    try {
        KeyStore ksTrust = KeyStore.getInstance("CRT");
        InputStream instream = context.getResources().openRawResource(R.raw.curl);
        ksTrust.load(instream, "secret".toCharArray());

        // TrustManager decides which certificate authorities to use.
        TrustManagerFactory tmf = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(ksTrust);
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, tmf.getTrustManagers(), null);

        client.sslSocketFactory(sslContext.getSocketFactory());
    } catch (KeyStoreException | IOException | NoSuchAlgorithmException | CertificateException | KeyManagementException e) {
        e.printStackTrace();
    }

    return client;
}

и мой журнал показывает это

 *

D/dalvikvm: DexOpt: unable to opt direct call 0x59ab at 0x08 in Lcom/google/android/gms/org/conscrypt/Platform;.wrapSSLSession
    I/ProviderInstaller: Installed default security provider GmsCore_OpenSSL
    D/testing: 0000000
    W/System.err: java.security.KeyStoreException: java.security.NoSuchAlgorithmException: KeyStore CRT implementation not found
            at java.security.KeyStore.getInstance(KeyStore.java:119)
            at com.example.z00402fj.token.RetrofitClient.enableTls12OnPreLollipop(RetrofitClient.java:94)
            at com.example.z00402fj.token.RetrofitClient.getClient(RetrofitClient.java:59)
            at com.example.z00402fj.token.MainActivity.onClick(MainActivity.java:66)
    W/System.err:     at android.view.View.performClick(View.java:4206)
            at android.view.View$PerformClick.run(View.java:17357)
            at android.os.Handler.handleCallback(Handler.java:725)
            at android.os.Handler.dispatchMessage(Handler.java:92)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:5045)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:818)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:584)
            at dalvik.system.NativeStart.main(Native Method)
        Caused by: java.security.NoSuchAlgorithmException: KeyStore CRT implementation not found
            at org.apache.harmony.security.fortress.Engine.notFound(Engine.java:177)
            at org.apache.harmony.security.fortress.Engine.getInstance(Engine.java:151)
            at java.security.KeyStore.getInstance(KeyStore.java:116)
            ... 14 more
    D/OkHttp: --> POST https://********/oauth/token http/1.1
        Content-Length: 0
        --> END POST (0-byte body)
    W/dalvikvm: VFY: unable to find class referenced in signature (Ljava/nio/file/Path;)
        VFY: unable to find class referenced in signature ([Ljava/nio/file/OpenOption;)
    I/dalvikvm: Could not find method java.nio.file.Files.newOutputStream, referenced from method okio.Okio.sink
    W/dalvikvm: VFY: unable to resolve static method 24869: Ljava/nio/file/Files;.newOutputStream (Ljava/nio/file/Path;[Ljava/nio/file/OpenOption;)Ljava/io/OutputStream;
    D/dalvikvm: VFY: replacing opcode 0x71 at 0x0002
    W/dalvikvm: VFY: unable to find class referenced in signature (Ljava/nio/file/Path;)
        VFY: unable to find class referenced in signature ([Ljava/nio/file/OpenOption;)
    I/dalvikvm: Could not find method java.nio.file.Files.newInputStream, referenced from method okio.Okio.source
    W/dalvikvm: VFY: unable to resolve static method 24868: Ljava/nio/file/Files;.newInputStream (Ljava/nio/file/Path;[Ljava/nio/file/OpenOption;)Ljava/io/InputStream;
    D/dalvikvm: VFY: replacing opcode 0x71 at 0x0002
    D/OkHttp: <-- HTTP FAILED: javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
    D/OkHttp: --> POST https://*************/oauth/token http/1.1
        Content-Length: 0
    D/OkHttp: --> END POST (0-byte body)
    D/OkHttp: --> POST https://*********.io/oauth/token http/1.1
        Content-Length: 0
        --> END POST (0-byte body)
    D/OkHttp: <-- HTTP FAILED: javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.

*

Ответы [ 2 ]

0 голосов
/ 19 декабря 2018
  Context context = null;

    try {
        // Create a trust manager that does not validate certificate chains
        final TrustManager[] trustAllCerts = new TrustManager[]{
                new X509TrustManager() {
                    @Override
                    public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
                    }

                    @Override
                    public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
                    }

                    @Override
                    public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                        return new java.security.cert.X509Certificate[]{};
                    }
                }
        };

        // Install the all-trusting trust manager
        final SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, trustAllCerts, new java.security.SecureRandom());

        // Create an ssl socket factory with our all-trusting manager
        final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();

        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.sslSocketFactory(sslSocketFactory, (X509TrustManager) trustAllCerts[0]);
        builder.hostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
        return builder;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

}

Наконец-то этот код запускается для меня

    ProviderInstaller.installIfNeededAsync(this, this);

Вы добавляете это в своей основной деятельности

0 голосов
/ 19 декабря 2018

Попробуйте использовать последнюю версию TLS v1.2 в своем классе Main Application.Это обеспечивается через пакет услуг Google Play со следующим кодом:

try {
    ProviderInstaller.installIfNeeded(getApplicationContext());
    SSLContext sslContext;
    sslContext = SSLContext.getInstance("TLSv1.2");
    sslContext.init(null, null, null);
    sslContext.createSSLEngine();
} catch (GooglePlayServicesRepairableException | GooglePlayServicesNotAvailableException |
 NoSuchAlgorithmException | KeyManagementException e) {
    e.printStackTrace();
}

try {
    ProviderInstaller.installIfNeeded(this);
} catch (GooglePlayServicesRepairableException e) {
    e.printStackTrace();
} catch (GooglePlayServicesNotAvailableException e) {
    e.printStackTrace();
}
...