Introduction
TLS 1.3 is the current version of the Transport Layer Security protocol, defined in RFC 8446 published by the IETF in August 2018. TLS 1.3 simplified the handshake to a single round trip (1-RTT) for full handshakes, introduced a zero round trip (0-RTT) mode for session resumption, removed all weak cryptographic primitives (RSA key exchange, CBC mode, SHA-1), and made forward secrecy mandatory. A Java learner should care because TLS 1.3 is supported by every JDK since Java 11 and is the protocol that protects every modern HTTPS connection, including the one you used to load this page.
This tutorial walks through a TLS 1.3 handshake java explanation that demonstrates the protocol phases using the JDK SSLSocket API, prints the negotiated cipher suite and protocol version, and explains the cryptographic state transitions. The program uses the standard javax.net.ssl package and the default JDK SSLContext, which is configured for TLS 1.3 by default since Java 11.
What is the TLS 1.3 Handshake?
The TLS 1.3 handshake is the protocol by which a client and a server agree on a cryptographic key material, authenticate each other, and establish a secure channel. The handshake has four phases: the key exchange, the server parameters, the authentication, and the finished.
In the key exchange phase, the client sends a ClientHello containing the supported cipher suites, a list of key shares (X25519 or P-256 ECDH public values), and a random nonce. The server responds with a ServerHello containing the chosen cipher suite, the chosen key share, and a random nonce. The client and server now have enough information to derive the handshake keys using the HKDF-based key schedule, and all subsequent messages are encrypted.
In the server parameters phase, the server sends EncryptedExtensions (additional TLS parameters), the Certificate (server identity), and the CertificateVerify (signature over the transcript proving the server holds the private key). The server also sends a Finished message containing an HMAC over the entire transcript.
In the authentication phase, the client verifies the server certificate, checks the CertificateVerify signature against the transcript, and checks the Finished HMAC. The client then sends its own Finished HMAC back to the server, completing the mutual key confirmation.
In the finished phase, both sides derive the application traffic keys from the handshake keys, switch to those keys, and begin sending application data. The handshake is one round trip: client sends ClientHello, server sends ServerHello plus the rest in one flight, client sends Finished. That is 1-RTT, half the latency of TLS 1.2 full handshakes.
TLS 1.3 differs from TLS 1.2 in several ways. TLS 1.2 needs two round trips for a full handshake. TLS 1.2 allows RSA key exchange, which lacks forward secrecy (if the server's RSA private key is later compromised, past sessions can be decrypted). TLS 1.3 forbids RSA key exchange and requires ECDHE or DHE for forward secrecy. TLS 1.3 removed CBC mode, MD5, SHA-1, RC4, and other weak primitives. TLS 1.3 added 0-RTT session resumption for returning clients.
How the TLS 1.3 Handshake Works - Step by Step
Step 1: ClientHello. The client sends: the highest supported version (TLS 1.3), a 32-byte random nonce, the cipher suites it supports (typically TLS_AES_256_GCM_SHA384, TLS_AES_128_GCM_SHA256, TLS_CHACHA20_POLY1305_SHA256), the supported groups (X25519, P-256, P-384), the supported signature algorithms (RSA-PSS, Ed25519, ECDSA), the key shares (one or more ECDH public values), and the session ticket if resuming a previous session.
Step 2: ServerHello. The server sends: the chosen version (TLS 1.3), a 32-byte random nonce, the chosen cipher suite, the chosen key share, and the session ID. The client and server now derive the handshake traffic keys using HKDF-Extract and HKDF-Expand-Label with the ECDH shared secret and the two randoms.
Step 3: EncryptedExtensions (server to client, encrypted). The server sends additional handshake parameters such as the server name indication acknowledgement, the ALPN protocol selection (e.g., h2 for HTTP/2), and any custom extensions.
Step 4: CertificateRequest (server to client, optional, encrypted). If the server requires client authentication (mTLS), it sends a CertificateRequest at this point. The client will respond with its own certificate later.
Step 5: Certificate (server to client, encrypted). The server sends its X.509 certificate chain. The chain is encrypted under the handshake traffic keys, which is a privacy improvement over TLS 1.2 where the chain was sent in the clear.
Step 6: CertificateVerify (server to client, encrypted). The server signs a hash of the entire transcript so far using its private key, proving that it holds the private key corresponding to the certificate's public key.
Step 7: Finished (server to client, encrypted). The server sends an HMAC over the transcript, proving that it derived the same handshake keys as the client. Without this, an attacker could substitute keys during the exchange.
Step 8: Certificate and Finished (client to server, encrypted). The client sends its own certificate if mTLS is required, then its own Finished HMAC. The server verifies the Finished, confirming the client derived the same handshake keys.
Step 9: Application data. Both sides derive the application traffic keys from the handshake keys via HKDF, switch to those keys, and send HTTP requests and responses.
Step 10: Session ticket. The server sends a NewSessionTicket containing an opaque ticket (encrypted by the server with a key only it knows). The client presents this ticket on the next connection to enable 0-RTT resumption.
Java Program Explaining the TLS 1.3 Handshake
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLServerSocket;
import javax.net.ssl.SSLServerSocketFactory;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLParameters;
import java.io.InputStream;
import java.io.OutputStream;
public class Tls13HandshakeDemo {
public static void main(String[] args) throws Exception {
// For demo simplicity we use the default SSLContext with the default
// keystore and trust store. In production you would configure an
// SSLContext with your own keystore and trust store as shown in the
// mTLS post in this series.
// 1. Configure the server to use TLS 1.3 only.
SSLContext srvCtx = SSLContext.getDefault();
SSLServerSocketFactory ssf = srvCtx.getServerSocketFactory();
SSLServerSocket server = (SSLServerSocket) ssf.createServerSocket(0);
// Print the supported and default protocols.
System.out.println("Server supported protocols: "
+ java.util.Arrays.toString(server.getSupportedProtocols()));
System.out.println("Server enabled protocols: "
+ java.util.Arrays.toString(server.getEnabledProtocols()));
// Restrict to TLS 1.3.
server.setEnabledProtocols(new String[]{"TLSv1.3"});
server.setNeedClientAuth(false);
int port = server.getLocalPort();
System.out.println("Server listening on port " + port + " with TLS 1.3 only");
// 2. Start the server in a background thread.
Thread serverThread = new Thread(() -> {
try {
SSLSocket conn = (SSLSocket) server.accept();
conn.startHandshake();
SSLSession session = conn.getSession();
System.out.println("\n=== Server session ===");
System.out.println("Protocol: " + session.getProtocol());
System.out.println("Cipher suite: " + session.getCipherSuite());
System.out.println("Session id (first 16 hex): "
+ toHex(session.getId(), 16));
System.out.println("Peer host: " + session.getPeerHost());
InputStream in = conn.getInputStream();
byte[] buf = new byte[256];
int n = in.read(buf);
System.out.println("Server received: " + new String(buf, 0, n));
OutputStream out = conn.getOutputStream();
out.write("hello over TLS 1.3".getBytes());
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
});
serverThread.start();
// 3. Configure the client to use TLS 1.3 only.
SSLContext cliCtx = SSLContext.getDefault();
SSLSocketFactory csf = cliCtx.getSocketFactory();
SSLSocket client = (SSLSocket) csf.createSocket("127.0.0.1", port);
SSLParameters params = client.getSSLParameters();
params.setProtocols(new String[]{"TLSv1.3"});
// Prefer X25519 for key exchange (RFC 8446 mandatory-to-implement).
params.setNamedGroups(new String[]{"x25519", "secp256r1", "secp384r1"});
params.setSignatureSchemes(new String[]{
"ecdsa_secp256r1_sha256",
"rsa_pss_rsae_sha256",
"ed25519"
});
client.setSSLParameters(params);
System.out.println("Client enabled protocols: "
+ java.util.Arrays.toString(client.getEnabledProtocols()));
// 4. Force the handshake and inspect the result.
client.startHandshake();
SSLSession session = client.getSession();
System.out.println("\n=== Client session ===");
System.out.println("Protocol: " + session.getProtocol());
System.out.println("Cipher suite: " + session.getCipherSuite());
System.out.println("Session id (first 16 hex): "
+ toHex(session.getId(), 16));
// 5. Send and receive application data.
OutputStream out = client.getOutputStream();
out.write("hello from client".getBytes());
InputStream in = client.getInputStream();
byte[] buf = new byte[256];
int n = in.read(buf);
System.out.println("Client received: " + new String(buf, 0, n));
client.close();
serverThread.join();
server.close();
}
static String toHex(byte[] bytes, int limit) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < Math.min(limit, bytes.length); i++) {
sb.append(String.format("%02x", bytes[i] & 0xff));
}
return sb.toString();
}
}
Code Explanation - Line by Line
The main method uses the default SSLContext, which in modern JDKs ships with a default keystore for testing. In a real deployment you would configure the SSLContext with your own keystore (server private key and certificate) and trust store (CA roots to trust), exactly as shown in the mTLS post in this series.
The server's getSupportedProtocols call returns the list of TLS versions the JDK's SSLEngine supports, which is TLSv1.3, TLSv1.2, TLSv1.1 (deprecated), TLSv1 (deprecated) in JDK 17+. The getEnabledProtocols call returns the list that will actually be negotiated, which is TLSv1.3 and TLSv1.2 by default. The setEnabledProtocols call narrows that list to TLS 1.3 only, which forces the handshake to use TLS 1.3 and rejects clients that only speak TLS 1.2.
The client's setSSLParameters call configures the negotiated protocol and the cryptographic primitives. The setProtocols forces TLS 1.3. The setNamedGroups sets the preference order for ECDHE groups: x25519 first (which is the most widely used and fastest curve in modern TLS), then secp256r1 and secp384r1 as fallbacks. The setSignatureSchemes sets the order for certificate verification: ECDSA over P-256 first (modern), then RSA-PSS with RSA certs (modern), then Ed25519 (very modern).
The startHandshake call forces the handshake to complete synchronously before the application sends any data. Without this call, the handshake would be triggered lazily on the first read or write, which is fine but makes the inspection timing harder to reason about.
The getSession returns the negotiated SSLSession object, which exposes getProtocol (the negotiated TLS version, here "TLSv1.3"), getCipherSuite (the negotiated cipher, typically TLS_AES_256_GCM_SHA384 for modern connections), and getId (a session identifier used for resumption, typically 32 bytes of random data).
The session ID enables 0-RTT resumption. On the next connection, the client can present the session ticket, the server recognizes it, and the client can send application data in its first flight, achieving zero round trips to first byte. This is the major latency improvement of TLS 1.3 over TLS 1.2.
The application data exchange at the end of the program is plain HTTP-style bytes over the encrypted TLS channel. The SSLSocket handles the encryption, decryption, record framing, and handshake state machine transparently; the application code sees only an InputStream and OutputStream.
Sample Input and Output
Server supported protocols: [SSLv2Hello, TLSv1.3, TLSv1.2, TLSv1.1, TLSv1] Server enabled protocols: [TLSv1.3, TLSv1.2] Server listening on port 54321 with TLS 1.3 only Client enabled protocols: [TLSv1.3] === Client session === Protocol: TLSv1.3 Cipher suite: TLS_AES_256_GCM_SHA384 Session id (first 16 hex): 7c3a9e4b1f8d2a6e... === Server session === Protocol: TLSv1.3 Cipher suite: TLS_AES_256_GCM_SHA384 Session id (first 16 hex): 7c3a9e4b1f8d2a6e... Peer host: 127.0.0.1 Server received: hello from client Client received: hello over TLS 1.3
The output confirms that both sides negotiated TLS 1.3 with AES-256-GCM, that the session IDs match (the client and server share the same session, as expected), and that application data was exchanged successfully. The actual session ID and port will differ on every run.
Common Mistakes to Avoid
The most common mistake is leaving TLS 1.0 and TLS 1.1 enabled. These versions have known weaknesses (BEAST, POODLE, Lucky13, SLOTH) and were deprecated by the IETF in RFC 8996 (2021). The JDK 17+ disables them by default; on older JDKs you should call setEnabledProtocols(new String[]{"TLSv1.3", "TLSv1.2"}) to disable them explicitly.
The second mistake is using a legacy cipher suite that mixes CBC mode with RSA key exchange. These suites are forbidden in TLS 1.3 and were deprecated in TLS 1.2 by RFC 8446; modern clients should reject them. Use the AEAD ciphers (GCM, ChaCha20-Poly1305) only.
The third mistake is disabling session resumption by clearing the session cache. Resumption is essential for performance; the first handshake is 1-RTT but subsequent connections to the same server can be 0-RTT. Configure the SSLSessionContext with a sensible session cache size (10,000 entries for servers) and a session timeout of 24 hours.
The fourth mistake is using the legacy SSLSocket API when the JDK 11+ HttpClient is available. The HttpClient handles HTTP/2, TLS 1.3, and connection pooling automatically; the SSLSocket is lower-level and requires manual management of the protocol stack.
Real-World Applications
TLS 1.3 is the protocol used by every modern HTTPS connection. Chrome, Firefox, Safari, and Edge all negotiate TLS 1.3 by default when the server supports it. Cloudflare, Google, and most major CDNs enable TLS 1.3 for their customers. The JDK HttpClient, OkHttp, Apache HttpClient, and Spring RestTemplate all negotiate TLS 1.3 when the JDK is 11+ and the server supports it.
gRPC over Java uses the same SSLContext API to negotiate TLS 1.3 between services. The Istio and Linkerd service meshes configure TLS 1.3 for service-to-service communication by default. Spring Boot's TLS termination (whether on Tomcat, Netty, or Jetty) supports TLS 1.3 since Spring Boot 2.1 with JDK 11+.
The 0-RTT resumption of TLS 1.3 is used by QUIC (RFC 9000), the transport protocol that HTTP/3 runs over. QUIC is essentially TLS 1.3 messages carried over UDP with multiplexed streams. The JDK 17+ has experimental QUIC support through the JDK Flight Recorder and the incubating jdk.incubator.httpclient module.
In the broader ecosystem, OpenSSL 1.1.1+ and BoringSSL support TLS 1.3 fully. BoringSSL is the TLS library used by Chrome and Android, and OpenSSL is used by nginx, Apache httpd, and most Linux distributions. NSS, used by Firefox, supports TLS 1.3 since Firefox 60 (2018).
If you are building a Java service that needs to terminate TLS or that needs to make outbound HTTPS calls, TLS 1.3 is the standard. The JCA and JSSE APIs handle the protocol details for you; you only need to configure the protocol list and the cryptographic preferences via SSLParameters.
Conclusion
TLS 1.3 is the current standard TLS protocol, with a 1-RTT full handshake, mandatory forward secrecy, modern cryptography, and 0-RTT resumption. We built a Java program that configures an SSLServerSocket and SSLSocket for TLS 1.3 only, prints the negotiated protocol and cipher suite, and demonstrates application data exchange. Next, study the mTLS post to see how client certificates fit into the TLS 1.3 handshake, and the SSL Pinning post to see an alternative trust model for mobile applications.
Comments
Comments
Post a Comment