TLS and HTTPS

suggest change

Transport Layer Security (TLS) and HTTPS secure network communications through encryption, data integrity checks, and peer identity authentication. On the JVM, Kotlin leverages standard cryptographic providers (javax.net.ssl) as well as modern networking frameworks like Ktor and OkHttp to configure secure client connections and HTTPS servers.


Core Concepts


HTTPS Client with OkHttp

OkHttp provides first-class support for configuring TLS specifications and certificate pinning.

Enforcing Modern TLS Protocols

import okhttp3.ConnectionSpec
import okhttp3.OkHttpClient
import okhttp3.TlsVersion

val modernTlsClient = OkHttpClient.Builder()
    .connectionSpecs(listOf(
        ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
            .tlsVersions(TlsVersion.TLS_1_3, TlsVersion.TLS_1_2)
            .build()
    ))
    .build()

Certificate Pinning

Certificate pinning ensures the client only talks to an endpoint whose certificate matches a pre-shared public key hash (SHA-256):

import okhttp3.CertificatePinner
import okhttp3.OkHttpClient
import okhttp3.Request

fun createPinnedClient(): OkHttpClient {
    val certificatePinner = CertificatePinner.Builder()
        .add("api.example.com", "sha256/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=")
        // Include backup pins to allow certificate rotation without breaking clients
        .add("api.example.com", "sha256/BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB=")
        .build()

    return OkHttpClient.Builder()
        .certificatePinner(certificatePinner)
        .build()
}

fun testPinnedConnection() {
    val client = createPinnedClient()
    val request = Request.Builder()
        .url("https://api.example.com/health")
        .build()

    client.newCall(request).execute().use { response ->
        println("HTTPS handshake succeeded: ${response.code}")
    }
}

Custom TrustStore in Standard Java HttpClient

If connecting to an internal corporate PKI or a server with an enterprise root CA, load the certificate into an SSLContext:

import java.io.File
import java.io.FileInputStream
import java.net.URI
import java.net.http.HttpClient
import java.net.http.HttpRequest
import java.net.http.HttpResponse
import java.security.KeyStore
import javax.net.ssl.SSLContext
import javax.net.ssl.TrustManagerFactory

fun createCustomTlsClient(trustStoreFile: File, trustStorePassword: CharArray): HttpClient {
    // 1. Load custom TrustStore
    val trustStore = KeyStore.getInstance(KeyStore.getDefaultType()).apply {
        FileInputStream(trustStoreFile).use { stream ->
            load(stream, trustStorePassword)
        }
    }

    // 2. Initialize TrustManagerFactory
    val tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()).apply {
        init(trustStore)
    }

    // 3. Create SSLContext enforcing TLSv1.3
    val sslContext = SSLContext.getInstance("TLSv1.3").apply {
        init(null, tmf.trustManagers, null)
    }

    // 4. Build standard HttpClient using custom SSLContext
    return HttpClient.newBuilder()
        .sslContext(sslContext)
        .build()
}

fun fetchSecureResource() {
    val client = createCustomTlsClient(File("custom-truststore.p12"), "changeit".toCharArray())
    val request = HttpRequest.newBuilder()
        .uri(URI.create("https://internal-service.local/metrics"))
        .GET()
        .build()

    val response = client.send(request, HttpResponse.BodyHandlers.ofString())
    println("Response: ${response.statusCode()}")
}

Configuring HTTPS in Ktor Server

Ktor Server supports embedding SSL/TLS certificates directly in code or through external application configuration (application.yaml / application.conf).

Programmatic SSL Configuration with Embedded Server

import io.ktor.server.application.*
import io.ktor.server.engine.*
import io.ktor.server.netty.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import java.io.File
import java.security.KeyStore

fun main() {
    val keyStoreFile = File("keystore.p12")
    val keyStorePassword = "keystore-password".toCharArray()
    val privateKeyPassword = "key-password".toCharArray()

    val keyStore = KeyStore.getInstance("PKCS12").apply {
        keyStoreFile.inputStream().use { stream ->
            load(stream, keyStorePassword)
        }
    }

    embeddedServer(Netty, configure = {
        // HTTP Connector for redirects (optional)
        connector {
            port = 8080
        }

        // HTTPS SSL Connector
        sslConnector(
            keyStore = keyStore,
            keyAlias = "mykey",
            keyStorePassword = { keyStorePassword },
            privateKeyPassword = { privateKeyPassword }
        ) {
            port = 8443
            keyStorePath = keyStoreFile
        }
    }) {
        routing {
            get("/") {
                call.respondText("Secure connection established over HTTPS!")
            }
        }
    }.start(wait = true)
}

Declarative Configuration (application.yaml)

ktor:
  deployment:
    sslPort: 8443
  security:
    ssl:
      keyStore: /etc/ssl/certs/keystore.p12
      keyAlias: mydomain
      keyStorePassword: ${KEYSTORE_PASSWORD}
      privateKeyPassword: ${KEY_PASSWORD}

Mutual TLS (mTLS)

In Zero Trust or service-to-service microservices, servers verify client certificates as well. In Kotlin:

  1. The client configures a KeyManagerFactory holding its private key and client certificate, and sends it during the TLS handshake.
  2. The server configures its TrustManagerFactory with the CA that signed the client certificates, requiring ClientAuth.REQUIRE.
import javax.net.ssl.KeyManagerFactory
import javax.net.ssl.SSLContext
import javax.net.ssl.TrustManagerFactory
import java.io.FileInputStream
import java.security.KeyStore

fun createMtlsContext(
    keyStorePath: String,
    keyStorePass: CharArray,
    trustStorePath: String,
    trustStorePass: CharArray
): SSLContext {
    val clientKeyStore = KeyStore.getInstance("PKCS12").apply {
        FileInputStream(keyStorePath).use { load(it, keyStorePass) }
    }
    val kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()).apply {
        init(clientKeyStore, keyStorePass)
    }

    val caTrustStore = KeyStore.getInstance("PKCS12").apply {
        FileInputStream(trustStorePath).use { load(it, trustStorePass) }
    }
    val tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()).apply {
        init(caTrustStore)
    }

    val sslContext = SSLContext.getInstance("TLSv1.3").apply {
        init(kmf.keyManagers, tmf.trustManagers, null)
    }
    return sslContext
}

Security Best Practices

  1. Never Disable Certificate Validation in Production: Bypassing SSL validation via dummy trust managers (X509TrustManager accepting all certificates) exposes communications to eavesdropping and MITM attacks.
  2. Use Modern KeyStore Formats: Standardize on PKCS12 (.p12) instead of proprietary .jks formats.
  3. Automate Certificate Rotation: When using certificate pinning, always maintain at least one backup pin pointing to an intermediate CA or secondary key pair.
  4. Enforce HSTS: Serve Strict-Transport-Security headers on all HTTPS endpoints to prevent protocol downgrade attacks.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents