I'm trying to implement mTLS in my Android application using a certificate stored in the Keychain. Here's the flow I'm following:
- I display a certificate picker to the user to select the desired certificate.
- I save the selected certificate and use it to configure an HTTP client.
However, I'm facing an issue. When attempting to establish the connection, I receive the following exception:
Caused by: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
It's worth noting that I've tested the same certificate by making a request where I load it from a file stored on the device, and in that case, the connection works correctly.
Here's the part of the code where I create the HTTP client:
actual fun clientWithMtls(block: HttpClientConfig<*>.() -> Unit) = HttpClient(OkHttp) {
val keyStore = KeyStore.getInstance(KeyStore.getDefaultType())
keyStore.load(null, null)
CertificateChain.certificateChain?.let{ x509Certificates ->
for ((index, cert) in x509Certificates.withIndex()) {
keyStore.setCertificateEntry("${CertificateChain.alias}-$index", cert)
}
}
val trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm())
trustManagerFactory.init(keyStore)
val sslContext = SSLContext.getInstance("TLS").apply {
init(null, trustManagerFactory.trustManagers,null)
}
engine {
preconfigured = OkHttpClient.Builder()
.sslSocketFactory(sslContext.socketFactory, trustManagerFactory.trustManagers.first() as X509TrustManager)
.build()
}
}
I tested it adding the keyManager to the sslContext initialization:
// Initialize KeyManagerFactory with the keystore
val keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm())
keyManagerFactory.init(
keyStore,
null
) // Assuming keys do not require additional passwords
val sslContext = SSLContext.getInstance("TLS").apply {
init(keyManagerFactory.keyManagers, trustManagerFactory.trustManagers, SecureRandom())
}
I'm reaching out to see if anyone has encountered a similar issue or has any ideas on how to resolve it.
Any suggestions would be greatly appreciated. Thanks in advance!