TLS and HTTPS
suggest changeTransport 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
- KeyStore: A secure container holding cryptographic keys and certificates (e.g., in PKCS12 format). Servers use key stores to present their identity to clients.
- TrustStore / TrustManager: Determines whether remote certificates and Certificate Authorities (CAs) should be trusted.
- TLS Protocols: Modern applications should enforce TLSv1.3 and TLSv1.2, while rejecting obsolete versions like SSLv3, TLS 1.0, and TLS 1.1.
- Certificate Pinning: Restricts accepted certificates or public keys to known hashes, guarding against compromised Certificate Authorities.
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:
- The client configures a
KeyManagerFactoryholding its private key and client certificate, and sends it during the TLS handshake. - The server configures its
TrustManagerFactorywith the CA that signed the client certificates, requiringClientAuth.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
- Never Disable Certificate Validation in Production: Bypassing SSL validation via dummy trust managers (
X509TrustManageraccepting all certificates) exposes communications to eavesdropping and MITM attacks. - Use Modern KeyStore Formats: Standardize on
PKCS12(.p12) instead of proprietary.jksformats. - Automate Certificate Rotation: When using certificate pinning, always maintain at least one backup pin pointing to an intermediate CA or secondary key pair.
- Enforce HSTS: Serve
Strict-Transport-Securityheaders on all HTTPS endpoints to prevent protocol downgrade attacks.