2

I'm working for an Android Kotlin project with self-signed SSL cert.

I use Okhttp for connection with server but my app crashes when try to access the server IP and error is saying I need to self sign certificate to access.

I already did many tests by searching internet resources but non of them works for my code. Check my following code and suggest me for better fix.

Please note the URL I put here just for Sample.

val client = OkHttpClient()
var url = "https://00.00.00.000"

            val requestBody = FormBody.Builder()
                    .add("phone", "+9500000000")
                    .add("token", "03AGdBq26rMv")
                    .build()

            val request = Request.Builder().url(url)
                    .header("User-Agent", "OkHttp Headers.java")
                    .addHeader("Content-Type", "application/json")
                    .addHeader("Accept", "application/json")
                    .post(requestBody)
                    .build()
            val response = client.newCall(request).execute()
            return response.body?.string().toString()
            println("Response" + response.body?.string().toString())
Aung Pyae
  • 85
  • 10
  • This discuss [link](https://stackoverflow.com/questions/23103174/does-okhttp-support-accepting-self-signed-ssl-certs) will help you about the work with self signed certificates and okhttp. – Jorge Alejandro Puñales Jan 22 '21 at 18:44

2 Answers2

3

The following code works for me when I put these few lines of code before building my Client connection.

//set self sign certificate
                val trustAllCerts = arrayOf<TrustManager>(object : X509TrustManager {
                    override fun checkClientTrusted(chain: Array<out X509Certificate>?, authType: String?) {
                    }

                    override fun checkServerTrusted(chain: Array<out X509Certificate>?, authType: String?) {
                    }

                    override fun getAcceptedIssuers() = arrayOf<X509Certificate>()
                })
                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

// connect to server
val client = OkHttpClient.Builder().sslSocketFactory(sslSocketFactory, trustAllCerts[0] as X509TrustManager).hostnameVerifier{ _, _ -> true }.build()
Aung Pyae
  • 85
  • 10
0

This example let's you connect to a known devserver using self signed certificates.

https://github.com/square/okhttp/blob/master/samples/guide/src/main/java/okhttp3/recipes/kt/DevServer.kt

  val clientCertificates = HandshakeCertificates.Builder()
      .addPlatformTrustedCertificates()
      .addInsecureHost(server.hostName)
      .build()

  val client = OkHttpClient.Builder()
      .sslSocketFactory(clientCertificates.sslSocketFactory(), clientCertificates.trustManager)
      .build()
Yuri Schimke
  • 12,435
  • 3
  • 35
  • 69