I use the SSL Socket and Trustmanager from this side Self signed SSL
but i keep getting following error:
09-28 19:52:41.942: WARN/System.err(1
In my case a following error raised on Android 4 and 5:
Caused by: com.android.org.bouncycastle.jce.exception.ExtCertPathValidatorException: Could not validate certificate: Certificate expired at Sat May 30 10:48:38 GMT+00:00 2020 (compared to Thu Aug 13 11:47:00 GMT+00:00 2020)
...
Caused by: java.security.cert.CertificateExpiredException: Certificate expired at Sat May 30 10:48:38 GMT+00:00 2020 (compared to Thu Aug 13 11:47:00 GMT+00:00 2020)
The server has certificate error (probably expired).
For Retrofit
see https://stackoverflow.com/a/60507560/2914140. If you use Fuel
as a REST library, see kotlin library that can do httpS connection without certificate verification (like curl --insecure).
You can trust all certificates, but it's dangerous.
import java.security.SecureRandom
import java.security.cert.X509Certificate
import javax.net.ssl.*
import javax.security.cert.CertificateException
companion object {
private val gson: Gson
private val retrofit: Retrofit
init {
val okHttpClient = getOkHttpBuilder().build()
gson = GsonBuilder().setLenient().create()
retrofit = Retrofit.Builder()
.baseUrl(BASE_URL)
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create(gson))
.build()
}
private fun getOkHttpBuilder(): OkHttpClient.Builder =
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
OkHttpClient().newBuilder()
} else {
getUnsafeOkHttpClient()
}
private fun getUnsafeOkHttpClient(): OkHttpClient.Builder =
try {
// Create a trust manager that does not validate certificate chains
val trustAllCerts: Array = arrayOf(
object : X509TrustManager {
@Throws(CertificateException::class)
override fun checkClientTrusted(chain: Array?,
authType: String?) = Unit
@Throws(CertificateException::class)
override fun checkServerTrusted(chain: Array?,
authType: String?) = Unit
override fun getAcceptedIssuers(): Array = arrayOf()
}
)
// Install the all-trusting trust manager
val sslContext: SSLContext = SSLContext.getInstance("SSL")
sslContext.init(null, trustAllCerts, SecureRandom())
// Create an ssl socket factory with our all-trusting manager
val sslSocketFactory: SSLSocketFactory = sslContext.socketFactory
val builder = OkHttpClient.Builder()
builder.sslSocketFactory(sslSocketFactory,
trustAllCerts[0] as X509TrustManager)
builder.hostnameVerifier { _, _ -> true }
builder
} catch (e: Exception) {
throw RuntimeException(e)
}
}
See also https://stackoverflow.com/a/60507560/2914140 for Android version check and Glide
connection.