SSLSocketFactory and TrustManager redundancy in OkHttp3
Asked Answered
Q

1

9

In OkHttp3, the following is deprecated [A]:

    sslSocketFactory(SSLSocketFactory sslSocketFactory) 

It is replaced by [B]:

    sslSocketFactory(SSLSocketFactory sslSocketFactory, X509TrustManager trustManager).

Here are my questions:


More info:

When creating a SSLSocketFactory object, it is already possible to specify a trustManager in

sslContext.init(KeyManager[] arg0, TrustManager[] arg1, SecureRandom arg2).

For example, I get a SSLSocketFactory object by doing:

public SSLSocketFactory getSSLSocketFactory() {
  SSLContext sslContext = SSLContext.getInstance("TLS");
  sslContext.init(getKeyManager(), getTrustManager(), new SecureRandom());
  return sslContext.getSocketFactory();
}

With getTrustManager() a method that returns a TrustManager[], which contains the servers' certificate the client should trust.

Now, since

sslSocketFactory(SSLSocketFactory sslSocketFactory, X509TrustManager trustManager) 

expects me to provide a X509TrustManager object, I deal with this by doing:

OkHttpClient okClient = new OkHttpClient.Builder().sslSocketFactory(getSSLSocketFactory(), (X509TrustManager) getTrustManager()[0]).build();

However, I have the feeling this is not how they were expecting us to use it. So any inputs are welcome.

Thanks.

Quizmaster answered 8/11, 2018 at 5:10 Comment(0)
S
0

The method uses reflection. The reason is stated in the OkHttp documentation:

/**
 * Sets the socket factory used to secure HTTPS connections. 
 * If unset, the system default will be used.
 *
 * @deprecated [SSLSocketFactory] does not expose its [X509TrustManager], which is
 *     a field that OkHttp needs to build a clean certificate chain. This method
 *     instead must use reflection to extract the trust manager. Applications should
 *     prefer to call `sslSocketFactory(SSLSocketFactory, X509TrustManager)`, 
 *     which avoids such reflection.
 */
Stadia answered 1/9, 2019 at 14:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.