1

I was trying to replicate this process of self-signed certificate process (link: https://www.baeldung.com/okhttp-self-signed-cert) in an android app that is using Kotlin. The problem is the implementation in the link I've provided is in Java and I can't seem to correctly convert this code to its Kotlin version.

sslContext.init(null, new TrustManager[] { TRUST_ALL_CERTS }, new java.security.SecureRandom());

This is how I implemented it in Kotlin:

val sslContext: SSLContext = SSLContext.getInstance("SSL")
.init(null, arrayOf(TRUST_ALL_CERTS) as Array<TrustManager>,
    java.security.SecureRandom()) as SSLContext

I casted the init to SSLContext because it is in Unit but after doing so, this warning appears:

this cast can never succeed

What could be an alternative fix for this one? Theoretically, it will cause an error once I publish it, and I want to avoid it. Please help. Thank you

Note: I can't test my app on my local machine because the app communicates with a server that will not allow the app to be ran locally.

Reb
  • 13
  • 2

2 Answers2

2

To do it atomically use apply

val sslContext: SSLContext = SSLContext.getInstance("SSL").apply {
  init(null, arrayOf<TrustManager>(TRUST_ALL_CERTS), java.security.SecureRandom())
}
Yuri Schimke
  • 12,435
  • 3
  • 35
  • 69
0

SSLContext.init() is returning void ( or Unit in Kotlin), so you are basically trying to cast Unit to SSLContext, which will never successed

You should seprate statements like this:

val sslContext: SSLContext = SSLContext.getInstance("SSL")
sslContext.init(null, arrayOf(TRUST_ALL_CERTS) as Array<TrustManager>,
    java.security.SecureRandom())
hiddeneyes02
  • 2,562
  • 1
  • 31
  • 58