Backporting TLS to older Android versions
Ensuring compatibility with legacy Android OS devices on Cobrowse by backporting TLS 1.2 and TLS 1.3.
Example of using a Conscrypt-based OkHttpClient with Cobrowse SDK
OkHttpClient with Cobrowse SDKdependencies {
...
implementation 'org.conscrypt:conscrypt-android:2.5.3'
}/**
* Builder of custom {@link OkHttpClient} which supports TLS v1.2 and TLS v1.3 on older platforms.
*/
public class ModernTlsOkHttpClient {
private static final String TAG = "ModernTlsOkHttpClient";
private static class ReusableSingleton {
private static final OkHttpClient INSTANCE = create();
private static final Provider CONSCRYPT = Conscrypt.newProvider();
}
private ModernTlsOkHttpClient() {
}
/**
* Returns an app-wide reusable {@link OkHttpClient} instance.
*/
public static OkHttpClient reuse() {
return ReusableSingleton.INSTANCE;
}
/**
* Returns an app-wide reusable {@link Provider} instance from Conscrypt.
*/
public static Provider conscrypt() {
return ReusableSingleton.CONSCRYPT;
}
/**
* Creates a new {@link OkHttpClient} instance.
*/
public static OkHttpClient create() {
OkHttpClient.Builder builder = new OkHttpClient.Builder()
.pingInterval(60, TimeUnit.SECONDS)
.connectTimeout(2000, TimeUnit.MILLISECONDS);
return enableModernTls(builder).build();
}
@NonNull
private static OkHttpClient.Builder enableModernTls(@NonNull OkHttpClient.Builder client) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
// No modifications on Android 10+
return client;
}
try {
X509TrustManager tm = Conscrypt.getDefaultX509TrustManager();
SSLContext sslContext = SSLContext.getInstance("TLS", conscrypt());
sslContext.init(null, new TrustManager[] { tm }, null);
client.sslSocketFactory(new ModernTlsSocketFactory(sslContext.getSocketFactory()), tm);
} catch (Exception e) {
Log.e(TAG, "Error while setting TLS", e);
}
return client;
}
}Last updated