最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

kotlin - Implementing mTLS in Android Using Certificate from Keychain: Trust anchor for certification path not found - Stack Ove

programmeradmin4浏览0评论

I'm trying to implement mTLS in my Android application using a certificate stored in the Keychain. Here's the flow I'm following:

  1. I display a certificate picker to the user to select the desired certificate.
  2. 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!

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论