0

I'm trying to connect to my API server using a self-signed certificate. The certificate was successfully installed on the server. I've tested it via OpenSSL and also in Firefox. I followed the Andrey Makarov's answer to configure OkHttp. But it doesn't work. When I try to execute my request I get javax.net.ssl.SSLHandshakeException with java.security.cert.CertPathValidatorException: Trust anchor for certification path not found message.

Here is my code:

public HttpClient() {

    /* ... */

    SSLContext sslContext = null;

    try {
        sslContext = SSLContext.getInstance("TLSv1.2");
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }

    KeyStore keyStore = readKeyStore();

    TrustManagerFactory trustManagerFactory = null;
    try {
        trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(keyStore);
        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keyStore, "password".toCharArray());
        sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), new SecureRandom());
    }
    catch (final Exception e) {
        Log.e(TAG, e.toString());
    }


    TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
    X509TrustManager trustManager = (X509TrustManager) trustManagers[0];


    OkHttpClient client = new OkHttpClient.Builder()
            .sslSocketFactory(sslContext.getSocketFactory(), trustManager)
            .build();

    mRetrofit = new Retrofit.Builder()
            .client(client)
            .baseUrl(mBaseUrl)
            .addConverterFactory(GsonConverterFactory.create())
            .build();
}

private KeyStore readKeyStore() {

    KeyStore ks = null;
    try {
        ks = KeyStore.getInstance("BKS");
    }
    catch (final Exception e) {
        Log.e(TAG, e.toString());
    }

    char[] password = "password".toCharArray();

    final Context context = App.app;
    InputStream is = context.getResources().openRawResource(R.raw.key_sorage);

    try {
        ks.load(is, password);
    }
    catch (final Exception e) {
        Log.e(TAG, e.toString());
    }
    finally {
        if (is != null) {
            try {
                is.close();
            }
            catch (final Exception e2) {
                Log.e(TAG, e2.toString());
            }
        }
    }

    return ks;
}

Retrofit version is 2.3.0.

Farhana Naaz Ansari
  • 7,524
  • 26
  • 65
  • 105
minimum y
  • 1
  • 1
  • Have you called get AcceptedIssuers to see if your certificate is in the trust store? –  Jul 19 '17 at 02:18
  • Do you mean trustManager.getAcceptedIssuers() method? It returns one X509CertificateObject object which looks like my cert. – minimum y Jul 19 '17 at 08:37

0 Answers0