Java SSL/TLS Sockets: SSLSocket and SSLServerSocket
TLS encrypts a TCP connection and lets the client verify who the server is. In Java, an SSLContext holds the keys a side presents and the certificates it trusts, and SSLSocket and SSLServerSocket are used like ordinary sockets. Most TLS problems are certificate trust problems, so this page shows both the working setup and the common failures.
Contents
How TLS protects a connection
TLS (Transport Layer Security, the successor of SSL) runs on top of a TCP connection and gives it three properties: confidentiality (nobody on the path can read the data), integrity (nobody can change it unnoticed) and authentication (the client knows it is talking to the real server, and optionally the server knows the client). Before any application data flows, the two sides run a handshake. In TLS 1.3 the client sends its supported cipher suites and a key share, the server answers with its own key share, its certificate and a signature proving it owns the certificate's private key, and both derive the same session keys. That costs one network round trip on top of TCP's. From then on, every record is encrypted and authenticated with AES-GCM or ChaCha20-Poly1305.
The certificate is what prevents interception. The client checks two things: that the certificate chains up to a certificate authority (CA) in its trust store, and that the certificate was issued for the host name it meant to reach. Skipping either check makes the encryption worthless, because an attacker can then present their own certificate.
| Version or feature | JDK status |
|---|---|
| SSLv3, TLS 1.0, TLS 1.1 | Disabled by default (TLS 1.0 and 1.1 since the April 2021 updates, all current releases) |
| TLS 1.2 | Enabled; supported since Java 7 |
| TLS 1.3 | Enabled and preferred; added in Java 11 (JEP 332) |
SSLSocketSSLServerSocketSSLContext | Since Java 1.4, when JSSE joined the JDK |
SSLEngine | Since Java 5, for TLS over NIO channels |
All programs ran on JDK 21. They create throwaway certificates with the JDK's keytool
A test certificate
A TLS server needs a private key and a certificate. For a self-contained demo, this helper runs the JDK's keytoollocalhost
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.KeyStore;
// Creates a self-signed certificate for "localhost" with the JDK's keytool, for the demos
final class TestCert {
private TestCert() {
}
static final char[] PASSWORD = "changeit".toCharArray();
static KeyStore create() throws Exception {
Path dir = Files.createTempDirectory("tls-demo");
Path ks = dir.resolve("server.p12");
String keytool = Path.of(System.getProperty("java.home"), "bin", "keytool").toString();
Process p = new ProcessBuilder(keytool, "-genkeypair", "-alias", "server",
"-keyalg", "EC", "-groupname", "secp256r1", "-validity", "1",
"-dname", "CN=localhost", "-ext", "SAN=dns:localhost",
"-keystore", ks.toString(), "-storetype", "PKCS12",
"-storepass", new String(PASSWORD))
.redirectErrorStream(true).start();
p.getInputStream().readAllBytes();
if (p.waitFor() != 0) {
throw new IllegalStateException("keytool failed");
}
KeyStore store = KeyStore.getInstance("PKCS12");
try (InputStream in = Files.newInputStream(ks)) {
store.load(in, PASSWORD);
}
Files.delete(ks);
Files.delete(dir);
return store;
}
}
A TLS echo server and client
Each side builds an SSLContext
- The server uses a
, which supplies the private key and certificate to present.KeyManagerFactory - The client uses a
, which decides which certificates to accept. Here it trusts exactly the test certificate; normally it uses the default CA list by passingTrustManagerFactory .null
After that, the sockets are used like plain TCP sockets (see
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.nio.charset.StandardCharsets;
import java.security.KeyStore;
import java.security.cert.X509Certificate;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLParameters;
import javax.net.ssl.SSLServerSocket;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.TrustManagerFactory;
public class TlsEcho {
public static void main(String[] args) throws Exception {
KeyStore serverKeys = TestCert.create();
// Server: presents its private key and certificate
KeyManagerFactory kmf = KeyManagerFactory.getInstance("PKIX");
kmf.init(serverKeys, TestCert.PASSWORD);
SSLContext serverCtx = SSLContext.getInstance("TLS");
serverCtx.init(kmf.getKeyManagers(), null, null);
// Client: trusts exactly this certificate (in production: the default CA list)
KeyStore trust = KeyStore.getInstance("PKCS12");
trust.load(null, null);
trust.setCertificateEntry("server", serverKeys.getCertificate("server"));
TrustManagerFactory tmf = TrustManagerFactory.getInstance("PKIX");
tmf.init(trust);
SSLContext clientCtx = SSLContext.getInstance("TLS");
clientCtx.init(null, tmf.getTrustManagers(), null);
InetAddress lo = InetAddress.getLoopbackAddress();
try (SSLServerSocket server = (SSLServerSocket) serverCtx.getServerSocketFactory()
.createServerSocket(0, 50, lo)) {
Thread.ofVirtual().start(() -> {
try (SSLSocket s = (SSLSocket) server.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(
s.getInputStream(), StandardCharsets.UTF_8));
PrintWriter out = new PrintWriter(s.getOutputStream(), true,
StandardCharsets.UTF_8)) {
out.println("secure echo: " + in.readLine());
} catch (Exception e) {
System.out.println("server: " + e);
}
});
try (SSLSocket client = (SSLSocket) clientCtx.getSocketFactory()
.createSocket("localhost", server.getLocalPort())) {
SSLParameters params = client.getSSLParameters();
params.setEndpointIdentificationAlgorithm("HTTPS"); // check the host name
client.setSSLParameters(params);
client.startHandshake();
var session = client.getSession();
X509Certificate cert = (X509Certificate) session.getPeerCertificates()[0];
System.out.println("protocol: " + session.getProtocol());
System.out.println("cipher suite: " + session.getCipherSuite());
System.out.println("server cert: " + cert.getSubjectX500Principal().getName()
+ ", key " + cert.getPublicKey().getAlgorithm());
PrintWriter out = new PrintWriter(client.getOutputStream(), true,
StandardCharsets.UTF_8);
out.println("hello over TLS");
System.out.println(new BufferedReader(new InputStreamReader(
client.getInputStream(), StandardCharsets.UTF_8)).readLine());
}
}
}
}
Output (on JDK 21):
protocol: TLSv1.3
cipher suite: TLS_AES_256_GCM_SHA384
server cert: CN=localhost, key EC
secure echo: hello over TLS
- The client and server negotiated TLS 1.3, the default in current JDKs, with AES-256-GCM.
makes the client check that the certificate was issued for the host it connected to. A plainsetEndpointIdentificationAlgorithm("HTTPS") does not do this by default (SSLSocket andHttpClient do). Without it, any certificate from a trusted CA, for any domain, would be accepted.HttpsURLConnection- The handshake runs on the first read or write if you do not call
yourself; calling it explicitly makes errors appear in a predictable place.startHandshake()
The two common handshake failures
The program connects to the same server three times: with the JDK's default trust store, with the pinned certificate and the right host name, and with the pinned certificate but connecting by IP address.
import java.net.InetAddress;
import java.security.KeyStore;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLHandshakeException;
import javax.net.ssl.SSLParameters;
import javax.net.ssl.SSLServerSocket;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.TrustManagerFactory;
public class TlsFailures {
static SSLContext clientTrusting(KeyStore trust) throws Exception {
TrustManagerFactory tmf = TrustManagerFactory.getInstance("PKIX");
tmf.init(trust); // null = the JDK's default CA list
SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(null, tmf.getTrustManagers(), null);
return ctx;
}
static void tryConnect(String label, SSLContext ctx, String host, int port) {
try (SSLSocket s = (SSLSocket) ctx.getSocketFactory().createSocket(host, port)) {
SSLParameters p = s.getSSLParameters();
p.setEndpointIdentificationAlgorithm("HTTPS");
s.setSSLParameters(p);
s.startHandshake();
System.out.println(label + ": handshake OK");
} catch (SSLHandshakeException e) {
String msg = e.getMessage();
System.out.println(label + ": SSLHandshakeException");
System.out.println(" " + msg.substring(msg.lastIndexOf(':') + 1).trim());
} catch (Exception e) {
System.out.println(label + ": " + e);
}
}
public static void main(String[] args) throws Exception {
KeyStore serverKeys = TestCert.create();
KeyManagerFactory kmf = KeyManagerFactory.getInstance("PKIX");
kmf.init(serverKeys, TestCert.PASSWORD);
SSLContext serverCtx = SSLContext.getInstance("TLS");
serverCtx.init(kmf.getKeyManagers(), null, null);
KeyStore pinned = KeyStore.getInstance("PKCS12");
pinned.load(null, null);
pinned.setCertificateEntry("server", serverKeys.getCertificate("server"));
try (SSLServerSocket server = (SSLServerSocket) serverCtx.getServerSocketFactory()
.createServerSocket(0, 50, InetAddress.getLoopbackAddress())) {
Thread.ofVirtual().start(() -> {
while (true) {
try (SSLSocket s = (SSLSocket) server.accept()) {
s.startHandshake();
} catch (Exception ignoredFailedHandshake) {
if (server.isClosed()) {
return;
}
}
}
});
int port = server.getLocalPort();
tryConnect("default CA list, self-signed cert", clientTrusting(null), "localhost",
port);
tryConnect("trusted cert, host \"localhost\"", clientTrusting(pinned), "localhost",
port);
tryConnect("trusted cert, host \"127.0.0.1\"", clientTrusting(pinned), "127.0.0.1",
port);
}
}
}
Output:
default CA list, self-signed cert: SSLHandshakeException
unable to find valid certification path to requested target
trusted cert, host "localhost": handshake OK
trusted cert, host "127.0.0.1": SSLHandshakeException
(certificate_unknown) No subject alternative names matching IP address 127.0.0.1 found
- "unable to find valid certification path to requested target": the certificate is not signed by any CA in the client's trust store. This is the full ending of the well-known "PKIX path building failed" error, seen with self-signed certificates, private company CAs, and servers that do not send their intermediate certificate. The fix is to add the right CA certificate to a trust store the client uses, never to disable checking.
- With the certificate trusted and the host name matching, the handshake succeeds.
- "No subject alternative names matching IP address": the certificate is trusted, but it was issued for
, and the client connected tolocalhost . Host names and IP addresses are matched against the certificate's SAN entries exactly.127.0.0.1
A "trust all certificates" TrustManager-Djavax.net.debug=ssl:handshake
Mutual TLS: client certificates
In ordinary TLS only the server proves its identity. With mutual TLS the server also demands a certificate from the client, which is common between internal services and in banking APIs. The program creates three key pairs: the server's, a client's that the server trusts, and a stranger's that it does not, and connects with each kind of client.
import java.net.InetAddress;
import java.security.KeyStore;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLServerSocket;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.TrustManagerFactory;
public class MutualTls {
static SSLContext context(KeyStore keys, KeyStore trusted) throws Exception {
KeyManagerFactory kmf = null;
if (keys != null) {
kmf = KeyManagerFactory.getInstance("PKIX");
kmf.init(keys, TestCert.PASSWORD);
}
TrustManagerFactory tmf = TrustManagerFactory.getInstance("PKIX");
tmf.init(trusted);
SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(kmf == null ? null : kmf.getKeyManagers(), tmf.getTrustManagers(), null);
return ctx;
}
static KeyStore trustOnly(KeyStore owner) throws Exception {
KeyStore t = KeyStore.getInstance("PKCS12");
t.load(null, null);
t.setCertificateEntry("peer", owner.getCertificate("server"));
return t;
}
static void attempt(String label, SSLContext clientCtx, int port) {
try (SSLSocket c = (SSLSocket) clientCtx.getSocketFactory()
.createSocket("localhost", port)) {
c.startHandshake();
c.getOutputStream().write('x');
int reply = c.getInputStream().read(); // the server answers after checks
System.out.println(label + ": " + (reply == 'k' ? "accepted" : "closed by server"));
} catch (Exception e) {
System.out.println(label + ": " + e.getClass().getSimpleName() + " (" + e.getMessage()
+ ")");
}
}
public static void main(String[] args) throws Exception {
KeyStore serverKeys = TestCert.create();
KeyStore clientKeys = TestCert.create(); // a second, independent key pair
KeyStore strangerKeys = TestCert.create(); // unknown to the server
SSLContext serverCtx = context(serverKeys, trustOnly(clientKeys));
InetAddress lo = InetAddress.getLoopbackAddress();
try (SSLServerSocket server = (SSLServerSocket) serverCtx.getServerSocketFactory()
.createServerSocket(0, 50, lo)) {
server.setNeedClientAuth(true); // demand a client certificate
Thread.ofVirtual().start(() -> {
while (!server.isClosed()) {
try (SSLSocket s = (SSLSocket) server.accept()) {
s.getInputStream().read();
System.out.println(" server sees client: "
+ s.getSession().getPeerPrincipal().getName());
s.getOutputStream().write('k');
} catch (Exception e) {
if (!server.isClosed()) {
System.out.println(" server: " + e.getClass().getSimpleName());
}
}
}
});
int port = server.getLocalPort();
attempt("client with its certificate", context(clientKeys, trustOnly(serverKeys)),
port);
attempt("client without a certificate", context(null, trustOnly(serverKeys)), port);
attempt("client with an unknown certificate", context(strangerKeys,
trustOnly(serverKeys)), port);
}
}
}
Output:
server sees client: CN=localhost
client with its certificate: accepted
server: SSLHandshakeException
client without a certificate: SocketException (Broken pipe)
client with an unknown certificate: SSLHandshakeException ((certificate_unknown) Received fatal alert: certificate_unknown)
makes a client certificate mandatory. The client with its ownsetNeedClientAuth(true) was accepted, and the server read the client's identity,KeyManager , fromCN=localhost . That name is what an application would use for authorization.getPeerPrincipal()- A client with no certificate failed with the TLS 1.3 alert
, and a client whose certificate the server's trust store does not contain failed withcertificate_required . Both sides saw ancertificate_unknown .SSLHandshakeException - In TLS 1.3 the client's certificate is checked after the client considers the handshake complete, so these failures appear on the client's first read rather than in
. Code must be ready for handshake errors at that point.startHandshake() asks for a certificate but accepts clients without one, for servers that serve both kinds.setWantClientAuth(true)
What a handshake costs, and protocol versions
A TLS handshake involves key exchange, a certificate check and a signature, so new connections are expensive. The program times 100 connections each over plain TCP and TLS 1.3 on loopback, after 20 warm-up connections, then restricts the client to older protocol versions. Every socket sets TCP_NODELAY
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.security.KeyStore;
import java.util.Arrays;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLServerSocket;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.TrustManagerFactory;
public class HandshakeCost {
static SSLContext client(KeyStore serverKeys) throws Exception {
KeyStore trust = KeyStore.getInstance("PKCS12");
trust.load(null, null);
trust.setCertificateEntry("server", serverKeys.getCertificate("server"));
TrustManagerFactory tmf = TrustManagerFactory.getInstance("PKIX");
tmf.init(trust);
SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(null, tmf.getTrustManagers(), null);
return ctx;
}
interface Connect {
void run() throws Exception;
}
static double ms(Connect c, int n) throws Exception {
for (int i = 0; i < 20; i++) {
c.run(); // warm-up
}
long t0 = System.nanoTime();
for (int i = 0; i < n; i++) {
c.run();
}
return (System.nanoTime() - t0) / (double) n / 1e6;
}
public static void main(String[] args) throws Exception {
KeyStore serverKeys = TestCert.create();
KeyManagerFactory kmf = KeyManagerFactory.getInstance("PKIX");
kmf.init(serverKeys, TestCert.PASSWORD);
SSLContext serverCtx = SSLContext.getInstance("TLS");
serverCtx.init(kmf.getKeyManagers(), null, null);
InetAddress lo = InetAddress.getLoopbackAddress();
try (SSLServerSocket tls = (SSLServerSocket) serverCtx.getServerSocketFactory()
.createServerSocket(0, 50, lo);
ServerSocket plain = new ServerSocket(0, 50, lo)) {
System.out.println("server protocols: " + Arrays.toString(tls.getEnabledProtocols())
+ ", cipher suites enabled: " + tls.getEnabledCipherSuites().length);
for (ServerSocket ss : new ServerSocket[] {tls, plain}) {
Thread.ofVirtual().start(() -> {
while (!ss.isClosed()) {
try (Socket s = ss.accept()) {
s.setTcpNoDelay(true);
s.getOutputStream().write(1); // completes the handshake
s.getInputStream().read();
} catch (Exception e) {
// client went away
}
}
});
}
SSLContext shared = client(serverKeys);
double tcp = ms(() -> {
try (Socket s = new Socket(lo, plain.getLocalPort())) {
s.getInputStream().read();
}
}, 100);
double reused = ms(() -> {
try (SSLSocket s = (SSLSocket) shared.getSocketFactory()
.createSocket("localhost", tls.getLocalPort())) {
s.setTcpNoDelay(true);
s.getInputStream().read();
}
}, 100);
double fresh = ms(() -> {
try (SSLSocket s = (SSLSocket) client(serverKeys).getSocketFactory()
.createSocket("localhost", tls.getLocalPort())) {
s.setTcpNoDelay(true);
s.getInputStream().read();
}
}, 100);
System.out.printf("plain TCP connect: %6.2f ms%n", tcp);
System.out.printf("TLS 1.3, one shared SSLContext: %6.2f ms%n", reused);
System.out.printf("TLS 1.3, new SSLContext per connection: %5.2f ms%n", fresh);
// A client limited to TLS 1.2 still connects; one limited to TLS 1.1 does not
for (String proto : new String[] {"TLSv1.2", "TLSv1.1"}) {
try (SSLSocket s = (SSLSocket) shared.getSocketFactory()
.createSocket("localhost", tls.getLocalPort())) {
s.setEnabledProtocols(new String[] {proto});
s.startHandshake();
System.out.println(proto + " only: " + s.getSession().getProtocol() + ", "
+ s.getSession().getCipherSuite());
} catch (Exception e) {
System.out.println(proto + " only: " + e.getClass().getSimpleName() + " ("
+ e.getMessage() + ")");
}
}
}
}
}
Output of the handshake timing run:
server protocols: [TLSv1.3, TLSv1.2], cipher suites enabled: 31
plain TCP connect: 0.19 ms
TLS 1.3, one shared SSLContext: 8.28 ms
TLS 1.3, new SSLContext per connection: 9.80 ms
TLSv1.2 only: TLSv1.2, TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384
TLSv1.1 only: SSLHandshakeException (No appropriate protocol (protocol is disabled or cipher suites are inappropriate))
- The server enabled TLS 1.3 and 1.2 only, with 31 cipher suites.
- A TLS connection took milliseconds against a fraction of a millisecond for plain TCP, even without network latency. Most of the time is public-key cryptography: the key exchange and the certificate signature. Over a real network, add one more round trip. This is why HTTP clients and connection pools keep TLS connections open and reuse them.
- Reusing one
was somewhat faster than creating a new one per connection, though the gap varied from run to run. Build the context once anyway: it loads and parses key stores, and it holds the session cache that lets resumed sessions skip work.SSLContext - A trap found while writing this program: without
, each connection took about 90 ms, because the small handshake messages ran into Nagle's algorithm and delayed acknowledgments, as explained on theTCP_NODELAYTCP sockets page . - A client limited to TLS 1.2 connected with an ECDHE-ECDSA-AES-256-GCM suite. A client limited to TLS 1.1 failed with "No appropriate protocol", because current JDKs disable TLS 1.1. Old servers that only speak TLS 1.0 or 1.1 fail the same way, and the right fix is upgrading them, not re-enabling old protocols in
.java.security
Configuration summary
| Need | Setting |
|---|---|
| Server certificate and key | KeyManagerFactory-Djavax.net.ssl.keyStore |
| Trusted CAs for a client | Default (the JDK's cacertsTrustManagerFactory-Djavax.net.ssl.trustStore |
| Host name checking on raw sockets | SSLParameters.setEndpointIdentificationAlgorithm("HTTPS") |
| Client certificates (mutual TLS) | Server: setNeedClientAuth(true)KeyManager |
| Restrict protocols | SSLParameters.setProtocols(new String[] {"TLSv1.3", "TLSv1.2"}) |
Key stores hold the material: PKCS12 has been the default key store type since Java 9 (JEP 229), replacing the Java-only JKS format, and the same .p12keytool -importcertkeytool -list -v
For TLS with HTTP, HttpClientHttpClient.newBuilder().sslContext(ctx)