如何为okHttp相互TLS连接添加SSL证书?

2022-05-09 00:00:00 ssl kotlin java okhttp retrofit
我已经有一个.pem和一个.key文件,我不想在本地安装/导入它,只告诉我的客户端使用它们,可以吗?它不是自签名证书

基本上,在我的卷发中,我正在做这样的事情:

curl --key mykey.key --cert mycert.pem https://someurl.com/my-endpoint

我已检查此答案

How to make https request with ssl certificate in Retrofit

这也https://github.com/square/okhttp/blob/master/samples/guide/src/main/java/okhttp3/recipes/CustomTrust.java(但可能没有意义,因为我没有获得所需类型的对象)

基本上我有我的okHttpClient

val okHttpClient = OkHttpClient.Builder()
    .sslSocketFactory(?, ?) //here I tried to call sslSocketFactory, trustManager following the example from the CustomTrust.java
    .build()

有什么解决方案吗?

我也检查了此文档,但仍然没有完成SSL部分,也没有完成示例

https://square.github.io/okhttp/https/#customizing-trusted-certificates-kt-java

所以我尝试这样做(基于okhttp示例)

private fun trustedCertificatesInputStream(): InputStream {
        val comodoRsaCertificationAuthority = (""
            + "-----BEGIN CERTIFICATE-----
" +
            "-----END CERTIFICATE-----")
        return Buffer()
            .writeUtf8(comodoRsaCertificationAuthority)
            .inputStream()
    }


    val loggingInterceptor = HttpLoggingInterceptor().apply {
        level = HttpLoggingInterceptor.Level.BODY
    }


    fun createClient() : OkHttpClient {

        val trustManager: X509TrustManager
        val sslSocketFactory: SSLSocketFactory
        try {
            trustManager = trustManagerForCertificates(trustedCertificatesInputStream())
            val sslContext = SSLContext.getInstance("TLS")
            sslContext.init(null, arrayOf<TrustManager>(trustManager), null)
            sslSocketFactory = sslContext.socketFactory



        } catch (e: GeneralSecurityException) {
            throw RuntimeException(e)
        }
        return OkHttpClient.Builder()
            .sslSocketFactory(sslSocketFactory, trustManager)
            .connectTimeout(45, TimeUnit.SECONDS)
            .readTimeout(45, TimeUnit.SECONDS)
            .protocols(listOf(Protocol.HTTP_1_1))
            .addInterceptor(loggingInterceptor)
            .build()
    }


    @Throws(GeneralSecurityException::class)
    private fun trustManagerForCertificates(input: InputStream): X509TrustManager {
        val certificateFactory: CertificateFactory = CertificateFactory.getInstance("X.509")
        val certificates: Collection<Certificate?> = certificateFactory.generateCertificates(input)
        val password = "password".toCharArray() // Any password will work.
        val keyStore = newEmptyKeyStore(password)

        for ((index, certificate) in certificates.withIndex()) {
            val certificateAlias = index.toString()
            keyStore.setCertificateEntry(certificateAlias, certificate)
        }
        // Use it to build an X509 trust manager.
        val keyManagerFactory: KeyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm())
        keyManagerFactory.init(keyStore, password)

        val trustManagerFactory: TrustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm())
        trustManagerFactory.init(keyStore)

        val trustManagers: Array<TrustManager> = trustManagerFactory.getTrustManagers()
        return trustManagers[0]!! as X509TrustManager
    }

    @Throws(GeneralSecurityException::class)
    private fun newEmptyKeyStore(password: CharArray): KeyStore {
        return try {
            val keyStore = KeyStore.getInstance(KeyStore.getDefaultType())
            val inputStream: InputStream? = null // By convention, 'null' creates an empty key store.
            keyStore.load(inputStream, password)
            keyStore
        } catch (e: IOException) {
            throw AssertionError(e)
        }

    }

我得到一个错误

javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

搜索错误似乎应该在本地安装SSL,但我应该避免这样做,因为我无法在服务器中以这种方式安装它,有什么方法可以让它工作吗?

TLS

我假定您要配置推荐答案相互身份验证,这就是它们密钥的用途?

查看okhttp-tls,其中包含将证书和私钥转换为相应Java对象的API。

相关文章