[Python] How to convert this Python code with a SSL client certificate to Kotlin & ktor?

Discussão em 'Python' iniciado por Stack, Setembro 1, 2025.

  1. Stack

    Stack Membro Participativo

    I have some Python code that makes a HTTP request:

    import requests

    response = requests.get(
    url,
    cert = tuple(clientCertPath, pkeyPath), // paths to crt.pem and pkey.pem
    verify = serverCertPath // path to server-ca.crt file
    )


    I'd like to rewrite this to Kotlin using ktor. This is what I've come up with so far:

    val serverCert = serverCertPath.inputStream().use {
    CertificateFactory.getInstance("X.509").generateCertificate(it) as X509Certificate
    }
    val keyStore = KeyStore.getInstance(...).apply {
    load(null, null)
    setCertificateEntry("serverCert", serverCert)
    }
    val trustManagerFactory = ... // init with keystore
    val sslContext = SSLContext.getInstance("TLS") // and init with above config
    val client = HttpClient(Java) {
    engine {
    config {
    sslContext(sslContext)
    }
    }
    }

    // So far so good. This server certificate config seems to work and cover the 'verify' parameter. Now for the other cert.

    val clientCert = CertificateFactory.getInstance("X.509").let {
    clientCertPath.inputStream().use { stream -> it.generateCertificate(stream) as X509Certificate }
    }

    client.request(url) {
    this.method = HttpMethod.Get
    // how to supply client cert?
    }


    And now I'm stuck. How do I apply the client certificate to the request? Either client-level configuration or request-level configuration would be fine with me. Also, I still haven't used the pkeyPath. Where do I do that?

    Continue reading...

Compartilhe esta Página