DEV Community

Ilias Paraskevopoulos
Ilias Paraskevopoulos

Posted on

Trying to @POST at a server url - getting Trust anchor for certification path not found

I am trying to make a post request with a body, with Retrofit and OkHttpClient in kotlin. The url is https and when I try to make the request I am getting the Trust anchor for certification path not found exception

Also in manifest I am using android:usesCleartextTraffic="false"

This is the way I am creating the sslSocketFactory and I am using a custom .crt file. I also have a .key file which i am not sure if i should use it. When i try the request with insomnia api client, I need both files to make a successful request.

`object RetrofitHelper {
fun getOkHttpClient(context: Context): OkHttpClient {

    val loggingInterceptor = HttpLoggingInterceptor()
    val client = OkHttpClient.Builder()
    client.followRedirects(false)
    client.followSslRedirects(false)
    client.connectTimeout(10, TimeUnit.SECONDS)
    client.callTimeout(20, TimeUnit.SECONDS)
    client.addInterceptor(loggingInterceptor)


    val cf = CertificateFactory.getInstance("X.509")
    val certificate = context.resources.openRawResource(R.raw.crtfile)
    val key = context.resources.openRawResource(R.raw.keyfile)

    try {
        val ca = cf.generateCertificate(certificate)
        val keyStoreType = KeyStore.getDefaultType()
        val keyFactory = KeyFactory.getInstance("RSA")

        val keyBytes = ByteArray(key.available())

        val keyStore = KeyStore.getInstance(keyStoreType)
        keyStore.load(null, null)
        keyStore.setCertificateEntry("ca", ca)
        val arrayOfCertificates = Array<Certificate>(1) { ca }

        keyStore.setKeyEntry("key", keyBytes, arrayOfCertificates)


        val tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm()
        val tmf = TrustManagerFactory.getInstance(tmfAlgorithm)

        tmf.init(keyStore)
        val sslContext = SSLContext.getInstance("TLS")
        sslContext.init(null, tmf.trustManagers, null)

        client.sslSocketFactory(
            sslContext.socketFactory,
            tmf.trustManagers[0] as X509TrustManager
        )

    } catch (e: Exception) {
        Log.d(TAG, "getOkHttpClient: " + e.localizedMessage)
    } finally {
        if (certificate != null) {
            certificate.close()
        }
    }
    return client.build()
}}`
Enter fullscreen mode Exit fullscreen mode

Top comments (0)