Use self-signed certificates in Android

We should always use valid certificates for our Infinity deployments, however, this is not always possible. We could have a very specific deployment in our lab or be waiting for the client to deliver the certificates.

In all these cases, we can use the following function to override the default TrustManager.

:warning: WARNING: This code is only for testing. Get rid of it as soon as possible and never include it in a production package.

So, instead of using:

val okHttpClient = OkHttpClient()

It’s possible to use this:

val okHttpClientUnsecure = getUnsecureOkHttpClient()

Here is the function that creates the OkHttpClient that not validate the certificate:

private fun getUnsecureOkHttpClient(): OkHttpClient {
    try {
        // Create a trust manager that does not validate certificate chains
        val trustAllCerts = arrayOf<TrustManager>(object : X509TrustManager {
            @Throws(CertificateException::class)
            override fun checkClientTrusted(
                chain: Array<java.security.cert.X509Certificate>,
                authType: String
            ) {
            }

            @Throws(CertificateException::class)
            override fun checkServerTrusted(
                chain: Array<java.security.cert.X509Certificate>,
                authType: String
            ) {
            }

            override fun getAcceptedIssuers(): Array<java.security.cert.X509Certificate> {
                return arrayOf()
            }
        })
        // Install the all-trusting trust manager
        val sslContext = SSLContext.getInstance("SSL")
        sslContext.init(null, trustAllCerts, java.security.SecureRandom())
        // Create an ssl socket factory with our all-trusting manager
        val sslSocketFactory = sslContext.socketFactory
        val builder = OkHttpClient.Builder()
        builder.sslSocketFactory(sslSocketFactory, trustAllCerts[0] as X509TrustManager)
        builder.hostnameVerifier(hostnameVerifier = HostnameVerifier { _, _ -> true })
        return builder.build()
    } catch (e: Exception) {
        throw RuntimeException(e)
    }
}