Java TLS Basics
Java TLS (Transport Layer Security) encrypts data travelling over a network connection and proves to the client that it is talking to the real server. Every https:// URL, secure database connection and secure mail server uses TLS.
Java supports TLS through the JSSE API in the javax.net.ssl package. This lesson explains what happens in a TLS handshake, shows how to inspect TLS settings, make HTTPS calls, load your own keystore and truststore, and build a TLS server and client. It uses the server.p12 and client-trust.p12 files created in Java KeyStore Basics, and the plain socket code from Java Socket Basics.
How TLS Works in Java
When a client connects to a TLS server, both sides first run a handshake. Only after a successful handshake does application data flow, and it is encrypted.
- The client says which TLS versions and cipher suites it supports.
- The server picks one and sends its certificate, signed by a certificate authority (CA).
- The client checks the certificate against its truststore and checks the host name.
- Both sides agree on fresh session keys. Everything after this point is encrypted.
Java uses two stores for this, and the names are easy to mix up:
| Store | Who needs it | What it holds | JSSE class |
|---|---|---|---|
| Keystore | The server (and a client in mutual TLS) | Its own private key and certificate | KeyManagerFactory |
| Truststore | The client (and a server in mutual TLS) | Certificates of CAs or servers it trusts | TrustManagerFactory |
The main JSSE classes are:
| Class | Purpose |
|---|---|
SSLContext | Factory for TLS sockets and engines; holds key and trust managers |
SSLSocket / SSLServerSocket | TLS versions of Socket and ServerSocket |
SSLSession | Details of an established connection: protocol, cipher suite, peer certificates |
SSLParameters | Settings such as allowed protocols and host name checking |
Note: The names "SSL" in JSSE classes are historical. SSL itself is obsolete and disabled in modern JDKs; the classes speak TLS.
Check Supported TLS Versions and Cipher Suites
The default SSLContext shows which TLS versions are enabled in your JDK. Modern JDKs enable only TLS 1.3 and TLS 1.2 by default.
import java.util.Arrays;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLParameters;
public class TlsDefaults {
public static void main(String[] args) throws Exception {
SSLContext context = SSLContext.getDefault();
SSLParameters defaults = context.getDefaultSSLParameters();
SSLParameters supported = context.getSupportedSSLParameters();
System.out.println("Protocol: " + context.getProtocol());
System.out.println("Enabled protocols: " + Arrays.toString(defaults.getProtocols()));
System.out.println("Supported protocols: " + Arrays.toString(supported.getProtocols()));
System.out.println("Enabled cipher suites: " + defaults.getCipherSuites().length);
System.out.println("First three suites:");
Arrays.stream(defaults.getCipherSuites()).limit(3).forEach(suite -> System.out.println(" " + suite));
}
}
Output (on JDK 25; details vary by version):
Protocol: Default
Enabled protocols: [TLSv1.3, TLSv1.2]
Supported protocols: [TLSv1.3, TLSv1.2, TLSv1.1, TLSv1, SSLv3, SSLv2Hello]
Enabled cipher suites: 31
First three suites:
TLS_AES_256_GCM_SHA384
TLS_AES_128_GCM_SHA256
TLS_CHACHA20_POLY1305_SHA256
How it works:
SSLContext.getDefault()returns the context Java uses for HTTPS when you do not configure anything. It trusts the CAs in the JDK'scacertsfile.getDefaultSSLParameters()lists what is enabled.getSupportedSSLParameters()lists everything the JDK could do, including old versions that are disabled by thejdk.tls.disabledAlgorithmssecurity property.- A cipher suite names the algorithms used for encryption and integrity. The first three are TLS 1.3 suites, which are always AEAD ciphers such as AES-GCM.
| TLS version | Status in current JDKs |
|---|---|
| TLS 1.3 | Enabled, preferred |
| TLS 1.2 | Enabled |
| TLS 1.1, TLS 1.0 | Disabled by default |
| SSLv3 | Disabled by default |
Make an HTTPS Request and Inspect the TLS Session
You rarely open TLS sockets by hand. The HttpClient from Java HTTP Client speaks TLS automatically, and the response tells you which TLS session was used.
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.security.cert.X509Certificate;
import javax.net.ssl.SSLSession;
public class HttpsSessionInfo {
public static void main(String[] args) throws Exception {
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder(URI.create("https://www.example.com/")).build();
HttpResponse<Void> response = client.send(request, HttpResponse.BodyHandlers.discarding());
System.out.println("Status: " + response.statusCode());
SSLSession session = response.sslSession().orElseThrow();
System.out.println("TLS version: " + session.getProtocol());
System.out.println("Cipher suite: " + session.getCipherSuite());
X509Certificate serverCert = (X509Certificate) session.getPeerCertificates()[0];
System.out.println("Server certificate: " + serverCert.getSubjectX500Principal().getName());
System.out.println("Issued by: " + serverCert.getIssuerX500Principal().getName());
System.out.println("Chain length: " + session.getPeerCertificates().length);
}
}
Output (certificate details change when the site renews its certificate):
Status: 200
TLS version: TLSv1.3
Cipher suite: TLS_AES_256_GCM_SHA384
Server certificate: CN=*.example.com
Issued by: CN=DigiCert Global G3 TLS ECC SHA384 2020 CA1,O=DigiCert Inc,C=US
Chain length: 2
How it works:
HttpClientuses the defaultSSLContext, so it trusts the public CAs incacertsand checks that the certificate matcheswww.example.com.response.sslSession()returns anOptional<SSLSession>. It is empty for plainhttp://URLs.getPeerCertificates()returns the chain the server sent: the server's own certificate first, then the intermediate CA. The root CA is not sent; the client already has it in its truststore.
What Happens When a Certificate Is Not Trusted
If the server certificate is expired, self-signed or issued for a different host, the handshake fails and Java throws an SSLHandshakeException. The badssl.com test site serves deliberately broken certificates you can try.
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import javax.net.ssl.SSLHandshakeException;
public class UntrustedCertificates {
static void tryUrl(HttpClient client, String url) {
try {
HttpRequest request = HttpRequest.newBuilder(URI.create(url)).build();
int status = client.send(request, HttpResponse.BodyHandlers.discarding()).statusCode();
System.out.println("OK " + status + " " + url);
} catch (SSLHandshakeException e) {
System.out.println("REJECTED " + url);
System.out.println(" reason: " + e.getMessage().lines().findFirst().orElse(""));
} catch (Exception e) {
System.out.println("ERROR " + url + " -> " + e);
}
}
public static void main(String[] args) {
HttpClient client = HttpClient.newHttpClient();
tryUrl(client, "https://badssl.com/");
tryUrl(client, "https://self-signed.badssl.com/");
tryUrl(client, "https://expired.badssl.com/");
tryUrl(client, "https://wrong.host.badssl.com/");
}
}
Output (exact messages vary by JDK version):
OK 200 https://badssl.com/
REJECTED https://self-signed.badssl.com/
reason: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
REJECTED https://expired.badssl.com/
reason: PKIX path validation failed: java.security.cert.CertPathValidatorException: validity check failed
REJECTED https://wrong.host.badssl.com/
reason: No subject alternative DNS name matching wrong.host.badssl.com found.
How it works:
- Self-signed: no CA in
cacertssigned the certificate, so Java cannot build a trust path ("PKIX path building failed"). - Expired: the path exists, but the certificate's validity dates are in the past.
- Wrong host: the certificate is valid, but none of its names match the host in the URL. This check stops a valid certificate for one site being used to impersonate another.
Note: Never "fix" these errors with a trust manager that accepts every certificate. That turns off the protection TLS gives you. Add the correct certificate to a truststore instead, as shown next.
Create an SSLContext With Your Own Keystore and Truststore
To run a TLS server, or to trust a private certificate, you build your own SSLContext. The steps are always the same: load the stores, create key and trust managers, and initialize the context.
Syntax:
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(keyStore, keyPassword);
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(trustStore);
SSLContext context = SSLContext.getInstance("TLS");
context.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
The helper class below wraps these steps. Later examples reuse it.
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.KeyStore;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
public class TlsContexts {
static KeyStore load(Path file, char[] password) throws Exception {
KeyStore store = KeyStore.getInstance("PKCS12");
try (InputStream in = Files.newInputStream(file)) {
store.load(in, password);
}
return store;
}
// Server side: presents its own certificate from the keystore
static SSLContext serverContext(Path keyStoreFile, char[] password) throws Exception {
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(load(keyStoreFile, password), password);
SSLContext context = SSLContext.getInstance("TLS");
context.init(kmf.getKeyManagers(), null, null);
return context;
}
// Client side: trusts only the certificates in the truststore
static SSLContext clientContext(Path trustStoreFile, char[] password) throws Exception {
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(load(trustStoreFile, password));
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, tmf.getTrustManagers(), null);
return context;
}
public static void main(String[] args) throws Exception {
char[] password = "changeit".toCharArray();
SSLContext server = serverContext(Path.of("server.p12"), password);
SSLContext client = clientContext(Path.of("client-trust.p12"), password);
System.out.println("Server context: " + server.getProtocol());
System.out.println("Client context: " + client.getProtocol());
System.out.println("Default managers algorithm: " + KeyManagerFactory.getDefaultAlgorithm()
+ " / " + TrustManagerFactory.getDefaultAlgorithm());
}
}
Output:
Server context: TLS
Client context: TLS
Default managers algorithm: SunX509 / PKIX
How it works:
KeyManagerFactoryreads the private key and certificate fromserver.p12. The server uses them to prove its identity.TrustManagerFactoryreadsclient-trust.p12. The client accepts only servers whose certificate chains lead to a certificate in that store.- Passing
nullfor a manager array means "use none" for key managers and "use the JDK default" for trust managers. The third argument ofinitis aSecureRandom;nullpicks the default strong source. SSLContext.getInstance("TLS")enables the JDK's default TLS versions, which today means TLS 1.3 and 1.2.
Build a TLS Echo Server and Client
With the two contexts ready, a TLS server and client look almost exactly like plain socket code. The difference is that the sockets come from SSLServerSocketFactory and SSLSocketFactory.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import javax.net.ssl.SSLParameters;
import javax.net.ssl.SSLServerSocket;
import javax.net.ssl.SSLSocket;
public class TlsEchoDemo {
public static void main(String[] args) throws Exception {
char[] password = "changeit".toCharArray();
var serverContext = TlsContexts.serverContext(Path.of("server.p12"), password);
var clientContext = TlsContexts.clientContext(Path.of("client-trust.p12"), password);
// Server: listens on a free port and echoes one line in upper case
SSLServerSocket serverSocket = (SSLServerSocket)
serverContext.getServerSocketFactory().createServerSocket(0);
int port = serverSocket.getLocalPort();
Thread serverThread = Thread.ofVirtual().start(() -> {
try (serverSocket; SSLSocket connection = (SSLSocket) serverSocket.accept();
var in = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
var out = new PrintWriter(connection.getOutputStream(), true, StandardCharsets.UTF_8)) {
out.println("ECHO: " + in.readLine().toUpperCase());
} catch (Exception e) {
System.out.println("Server error: " + e.getMessage());
}
});
// Client: connects, turns on host name checking, sends one line
try (SSLSocket socket = (SSLSocket) clientContext.getSocketFactory().createSocket("localhost", port)) {
SSLParameters parameters = socket.getSSLParameters();
parameters.setEndpointIdentificationAlgorithm("HTTPS"); // check the certificate matches "localhost"
socket.setSSLParameters(parameters);
socket.startHandshake();
System.out.println("Handshake done: " + socket.getSession().getProtocol()
+ " with " + socket.getSession().getCipherSuite());
var out = new PrintWriter(socket.getOutputStream(), true, StandardCharsets.UTF_8);
var in = new BufferedReader(new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8));
out.println("hello over tls");
System.out.println("Server replied: " + in.readLine());
}
serverThread.join();
}
}
Output:
Handshake done: TLSv1.3 with TLS_AES_256_GCM_SHA384
Server replied: ECHO: HELLO OVER TLS
How it works:
createServerSocket(0)opens a TLS server socket on a free port. The server thread is a virtual thread, so the demo needs only one program.- The client creates an
SSLSocketfrom its own context, which trusts only the certificate inclient-trust.p12. setEndpointIdentificationAlgorithm("HTTPS")turns on host name verification. RawSSLSocketdoes not check host names unless you ask;HttpClientalways does.startHandshake()runs the handshake explicitly. Reading or writing would also start it, but calling it first gives clearer errors.- After the handshake, the streams work exactly like normal socket streams. The bytes on the wire are encrypted.
Note: The certificate in
server.p12listslocalhostand127.0.0.1in its SAN extension. If you connect with another host name, host name verification fails withNo name matching ... found.
Restrict TLS Versions and Debug the Handshake
You can limit a socket to specific protocols with setEnabledProtocols. This is useful when a server must support only TLS 1.3. The example also shows what a version mismatch looks like.
import java.nio.file.Path;
import javax.net.ssl.SSLHandshakeException;
import javax.net.ssl.SSLServerSocket;
import javax.net.ssl.SSLSocket;
public class TlsVersionMismatch {
public static void main(String[] args) throws Exception {
char[] password = "changeit".toCharArray();
var serverContext = TlsContexts.serverContext(Path.of("server.p12"), password);
var clientContext = TlsContexts.clientContext(Path.of("client-trust.p12"), password);
SSLServerSocket serverSocket = (SSLServerSocket) serverContext.getServerSocketFactory().createServerSocket(0);
serverSocket.setEnabledProtocols(new String[] {"TLSv1.3"}); // server accepts TLS 1.3 only
Thread.ofVirtual().start(() -> {
try (serverSocket; SSLSocket connection = (SSLSocket) serverSocket.accept()) {
connection.startHandshake();
} catch (Exception ignored) {
// the failed handshake also ends up here
}
});
try (SSLSocket socket = (SSLSocket) clientContext.getSocketFactory()
.createSocket("localhost", serverSocket.getLocalPort())) {
socket.setEnabledProtocols(new String[] {"TLSv1.2"}); // client offers TLS 1.2 only
socket.startHandshake();
System.out.println("Connected with " + socket.getSession().getProtocol());
} catch (SSLHandshakeException e) {
System.out.println("Handshake failed: " + e.getMessage());
}
}
}
Output:
Handshake failed: (protocol_version) Received fatal alert: protocol_version
How it works:
- The server enables only
TLSv1.3, and the client offers onlyTLSv1.2. They have no version in common. - The server sends a
protocol_versionalert, and the client throwsSSLHandshakeException. Change the client toTLSv1.3and the connection succeeds.
When a handshake fails and the message is not clear, turn on JSSE debug logging with a system property:
java -Djavax.net.debug=ssl:handshake TlsVersionMismatch
Output (shortened):
javax.net.ssl|DEBUG|...|ClientHello.java|Produced ClientHello handshake message (
"ClientHello": {
"client version" : "TLSv1.2",
...
javax.net.ssl|ERROR|...|TransportContext.java|Fatal (PROTOCOL_VERSION): Received fatal alert: protocol_version
How it works:
-Djavax.net.debug=ssl:handshakeprints every handshake message, so you can see which versions, cipher suites and certificates each side sent.- Use
-Djavax.net.debug=allfor even more detail. Turn debugging off in production, because the output is very large.
Real-World Example: HTTPS Client That Trusts a Private Server
Company APIs often use certificates from an internal CA that public browsers do not trust. This example builds an HttpClient that trusts both the normal public CAs and one extra private certificate, starts a small HTTPS server with the JDK's built-in HttpsServer, and calls it.
import com.sun.net.httpserver.HttpsConfigurator;
import com.sun.net.httpserver.HttpsServer;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.time.Duration;
import java.util.Collections;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
public class PrivateApiClient {
// Trust store = all JDK CAs + every certificate from an extra truststore
static SSLContext publicPlusPrivateTrust(Path extraTrustStore, char[] password) throws Exception {
KeyStore combined = KeyStore.getInstance(KeyStore.getDefaultType());
Path cacerts = Path.of(System.getProperty("java.home"), "lib", "security", "cacerts");
try (InputStream in = Files.newInputStream(cacerts)) {
combined.load(in, "changeit".toCharArray());
}
KeyStore extra = TlsContexts.load(extraTrustStore, password);
for (String alias : Collections.list(extra.aliases())) {
Certificate certificate = extra.getCertificate(alias);
combined.setCertificateEntry("private-" + alias, certificate);
}
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(combined);
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, tmf.getTrustManagers(), null);
return context;
}
public static void main(String[] args) throws Exception {
char[] password = "changeit".toCharArray();
// 1. A private HTTPS API using the self-signed certificate from server.p12
HttpsServer server = HttpsServer.create(new InetSocketAddress("localhost", 0), 0);
server.setHttpsConfigurator(new HttpsConfigurator(TlsContexts.serverContext(Path.of("server.p12"), password)));
server.createContext("/api/health", exchange -> {
byte[] body = "{\"status\":\"UP\"}".getBytes(StandardCharsets.UTF_8);
exchange.getResponseHeaders().add("Content-Type", "application/json");
exchange.sendResponseHeaders(200, body.length);
exchange.getResponseBody().write(body);
exchange.close();
});
server.start();
URI healthUrl = URI.create("https://localhost:" + server.getAddress().getPort() + "/api/health");
// 2. Default client: does not trust the private certificate
try {
HttpClient.newHttpClient().send(HttpRequest.newBuilder(healthUrl).build(),
HttpResponse.BodyHandlers.ofString());
} catch (javax.net.ssl.SSLHandshakeException e) {
System.out.println("Default client: rejected (certificate not trusted)");
}
// 3. Client with public + private trust
HttpClient trustedClient = HttpClient.newBuilder()
.sslContext(publicPlusPrivateTrust(Path.of("client-trust.p12"), password))
.connectTimeout(Duration.ofSeconds(5))
.build();
HttpResponse<String> privateResponse = trustedClient.send(
HttpRequest.newBuilder(healthUrl).build(), HttpResponse.BodyHandlers.ofString());
System.out.println("Private API: " + privateResponse.statusCode() + " " + privateResponse.body()
+ " via " + privateResponse.sslSession().orElseThrow().getProtocol());
// 4. The same client still works for public sites
HttpResponse<Void> publicResponse = trustedClient.send(
HttpRequest.newBuilder(URI.create("https://www.example.com/")).build(),
HttpResponse.BodyHandlers.discarding());
System.out.println("Public site: " + publicResponse.statusCode());
server.stop(0);
}
}
Output:
Default client: rejected (certificate not trusted)
Private API: 200 {"status":"UP"} via TLSv1.3
Public site: 200
How it works:
- Private server.
HttpsServerfrom thejdk.httpservermodule serves/api/healthover TLS, using the server context built fromserver.p12. - Default client fails. The default
HttpClienttrusts only the JDK'scacerts, and the self-signed certificate is not in it, so the handshake is rejected. - Combined truststore.
publicPlusPrivateTrustloadscacertsinto memory and adds every certificate fromclient-trust.p12withsetCertificateEntry. The file on disk is not changed. - One client for both.
HttpClient.newBuilder().sslContext(...)uses the combined trust managers, so the same client reaches the private API and public sites, and host name checks stay switched on for both.
In production, the extra certificate would be your company's internal CA certificate, so every internal server it signs is trusted automatically.