OkHttp 3.11 and TLS 1.2 support

生来就可爱ヽ(ⅴ<●) 提交于 2020-02-22 07:18:25

问题


The support for TLS v1.2 was added in Android 4.2, but it wasn't enabled by default. This issue was quite easy to fix with OkHttp 3.x by providing a custom SSLSocketFactory implementation to the OkHttp client:

OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.setSocketFactory(new MySSLSocketFactory());

In my case the custom socket factory was setting the enabled protocols like this:

private static final String[] TLS_PROTOCOLS = new String[]{ "TLSv1.1", "TLSv1.2" };

public MySSLSocketFactory(final KeyManager[] keyManagers, final TrustManager trustManager) throws KeyManagementException, NoSuchAlgorithmException {
  final SSLContext sslContext = SSLContext.getInstance(TLS);
  sslContext.init(keyManagers, new TrustManager[]{ trustManager }, null);
  // ...
}

// ...

private Socket enableTLSOnSocket(final Socket socket) {
  if (socket instanceof SSLSocket) {
    ((SSLSocket) socket).setEnabledProtocols(TLS_PROTOCOLS);
  }
  return socket;
}

In the latest OkHttp 3.11 we can read

Fix: Prefer TLSv1.2 where it is available. On certain older platforms it is necessary to opt-in to TLSv1.2

I was trying to check relevant commits (probably this one) but I'm not sure if it addresses the same issue as the custom factory does.

So my question is: is it safe to remove custom SSLSocketFactory when OkHttp 3.11+ is used to keep TSL 1.2 usage on old Android devices?


回答1:


I've tested the latest (3.11) OkHttp version with default socket factory

final SSLContext sslContext = SSLContext.getInstance(TLS); sslContext.init(keyManagers, new TrustManager[]{ trustManager }, null); sslContext.getSocketFactory();

Unfortunately, TLSv1.2 isn't preferred even though it is available. For now, I have to keep using my own implementation of SSLSocketFactory which includes TLSv1.2.



来源:https://stackoverflow.com/questions/52328897/okhttp-3-11-and-tls-1-2-support

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!