Java security and TLS

Java's security APIs are built on pluggable providers that supply algorithms, and its TLS implementation, JSSE, combines them with keystores to secure connections. In TLS, two objects decide the outcome: KeyManagers, which hold your own private key, and TrustManagers, which decide which certificates to accept. This page explains that architecture, lists what this JDK provides, runs a real TLS server and client in one program, and reproduces the hostname, mutual TLS and protocol mistakes that cause most TLS failures.

Contents

How Java's security APIs fit together

The Java Cryptography Architecture (JCA) separates what you ask for from who implements it. Code calls a factory such as MessageDigest.getInstance("SHA-256"), and the JDK asks each registered provider, in priority order, whether it implements that algorithm. The JDK ships with providers such as SUN, SunJCE and SunEC; others, such as Bouncy Castle or a hardware security module through PKCS#11, can be added without changing calling code. The cryptographic building blocks have their own pages: message digests, HMAC, AES, RSA and SecureRandom and PBKDF2.

TLS (Transport Layer Security) combines those blocks to protect a connection. During the handshake, the server sends its certificate chain, the client checks that the chain leads to a certificate it trusts and that the certificate names the host it wanted, and both sides agree on keys. After that, data is encrypted and integrity-protected. Java's implementation, JSSE, is configured through an SSLContext built from two parts:

  • KeyManagers hold your own private key and certificate, read from a KeyStore. A server always needs them; a client needs them only for mutual TLS.
  • TrustManagers decide which certificates from the other side to accept, usually by checking them against a trust store of certificate authorities. The JDK's default trust store is lib/security/cacerts.
The pieces and when they arrived
PieceSinceNotes
JCA providers, MessageDigest, SignatureJava 1.1Algorithms by name, implementations pluggable
JCE: Cipher, Mac, KeyAgreementJava 1.4 (bundled)Encryption; see the crypto pages
JSSE: SSLContext, SSLSocket, SSLEngineJava 1.4 (bundled)TLS for sockets and non-blocking I/O
PKCS12 as the default keystore typeJava 9 (JEP 229)Replaced the Java-only JKS format
TLS 1.3Java 11 (JEP 332)Faster handshake, only modern cipher suites
TLS 1.0 and 1.1 disabled by defaultJava 16, also in later 8 and 11 updatesListed in jdk.tls.disabledAlgorithms
Security Manager deprecated, then disabledDeprecated for removal in Java 17 (JEP 411); permanently disabled in Java 24 (JEP 486)Sandboxing untrusted code is no longer a JDK feature

The TLS examples were run on JDK 21. The TLS programs create throw-away keys with keytool and talk to themselves over localhost, so they need no network.

Providers, algorithms and TLS defaults

The program lists the installed providers, asks for a few algorithms, including two that this JDK does not have, and prints the TLS defaults.

Java
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.Provider;
import java.security.Security;
import java.util.List;
import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLParameters;

public class Providers {

    public static void main(String[] args) throws Exception {
        // 1. The JCA provider list, in priority order
        System.out.println("providers:");
        for (Provider p : Security.getProviders()) {
            System.out.printf("  %-10s %s%n", p.getName(), p.getVersionStr());
        }

        // 2. getInstance asks the providers in order; the first one that has it wins
        MessageDigest sha = MessageDigest.getInstance("SHA-256");
        Cipher gcm = Cipher.getInstance("AES/GCM/NoPadding");
        System.out.println("SHA-256 from " + sha.getProvider().getName()
                + ", AES/GCM from " + gcm.getProvider().getName());
        for (String alg : List.of("SHA3-256", "MD5", "BLAKE2b-512")) {
            try {
                MessageDigest.getInstance(alg);
                System.out.println("  " + alg + ": available");
            } catch (NoSuchAlgorithmException e) {
                System.out.println("  " + alg + ": NoSuchAlgorithmException");
            }
        }
        try {
            Cipher.getInstance("AES/XYZ/NoPadding");
        } catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
            System.out.println("  AES/XYZ: " + e.getClass().getSimpleName());
        }

        // 3. TLS defaults of this JDK
        SSLParameters defaults = SSLContext.getDefault().getDefaultSSLParameters();
        System.out.println("default TLS protocols: " + List.of(defaults.getProtocols()));
        System.out.println("first 3 default cipher suites: "
                + List.of(defaults.getCipherSuites()).subList(0, 3));
        String disabled = Security.getProperty("jdk.tls.disabledAlgorithms");
        System.out.println("jdk.tls.disabledAlgorithms starts with: "
                + disabled.substring(0, disabled.indexOf(',', disabled.indexOf(',') + 1)));
    }
}

Output:

Output
providers:
  SUN        21
  SunRsaSign 21
  SunEC      21
  SunJSSE    21
  SunJCE     21
  SunJGSS    21
  SunSASL    21
  XMLDSig    21
  SunPCSC    21
  JdkLDAP    21
  JdkSASL    21
  SunPKCS11  21
SHA-256 from SUN, AES/GCM from SunJCE
  SHA3-256: available
  MD5: available
  BLAKE2b-512: NoSuchAlgorithmException
  AES/XYZ: NoSuchAlgorithmException
default TLS protocols: [TLSv1.3, TLSv1.2]
first 3 default cipher suites: [TLS_AES_256_GCM_SHA384, TLS_AES_128_GCM_SHA256, TLS_CHACHA20_POLY1305_SHA256]
jdk.tls.disabledAlgorithms starts with: SSLv3, TLSv1
  • The providers are listed in priority order; getInstance returns the implementation of the first one that supports the algorithm. SHA-256 came from SUN and AES/GCM from SunJCE. Security.insertProviderAt or the security.provider.N entries in java.security change the order.
  • SHA3-256 (Java 9) and MD5 are available; BLAKE2b is not in the JDK, so getInstance threw NoSuchAlgorithmException. MD5 being available does not make it safe: it is broken for signatures and passwords and should be used only for checksums against accidental change.
  • The default TLS protocols are TLS 1.3 and 1.2, and the first cipher suites are the three TLS 1.3 suites. jdk.tls.disabledAlgorithms, a security property in conf/security/java.security, starts with SSLv3 and TLSv1, which is why old protocols fail even if code asks for them.

A TLS server and client in one program

keytool creates an EC key pair and a self-signed certificate for localhost. A server uses it as its identity, one client trusts that exact certificate, and a second client uses the JDK's default trust store, which has never heard of it.

Java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.KeyStore;
import java.security.cert.X509Certificate;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLHandshakeException;
import javax.net.ssl.SSLServerSocket;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.TrustManagerFactory;

public class LocalTls {

    static final String PASSWORD = "changeit";

    public static void main(String[] args) throws Exception {
        Path keystore = createSelfSignedKeystore();
        KeyStore ks = KeyStore.getInstance("PKCS12");
        try (InputStream in = Files.newInputStream(keystore)) {
            ks.load(in, PASSWORD.toCharArray());
        }
        X509Certificate cert = (X509Certificate) ks.getCertificate("server");
        System.out.println("certificate: " + cert.getSubjectX500Principal().getName()
                + ", key algorithm " + cert.getPublicKey().getAlgorithm());

        SSLContext serverCtx = serverContext(ks);
        SSLContext clientCtx = clientContextTrusting(cert);

        try (SSLServerSocket server = (SSLServerSocket)
                serverCtx.getServerSocketFactory().createServerSocket(0)) {
            Thread serverThread = new Thread(() -> serveTwice(server));
            serverThread.start();
            int port = server.getLocalPort();

            // A client that trusts this certificate
            try (SSLSocket socket = (SSLSocket) clientCtx.getSocketFactory()
                    .createSocket("localhost", port)) {
                socket.startHandshake();
                System.out.println("handshake ok: " + socket.getSession().getProtocol()
                        + ", " + socket.getSession().getCipherSuite());
                BufferedReader in = new BufferedReader(
                        new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8));
                System.out.println("server said: " + in.readLine());
            }

            // A client with the JDK's default trust store does not know this certificate
            try (SSLSocket socket = (SSLSocket) SSLContext.getDefault().getSocketFactory()
                    .createSocket("localhost", port)) {
                socket.startHandshake();
            } catch (SSLHandshakeException e) {
                System.out.println("default trust store: SSLHandshakeException, "
                        + "PKIX path building failed = "
                        + e.getMessage().contains("PKIX path building failed"));
            }
            serverThread.join();
        }
    }

    // keytool -genkeypair creates a private key and a self-signed certificate
    static Path createSelfSignedKeystore() throws IOException, InterruptedException {
        Path keystore = Files.createTempDirectory("tls").resolve("server.p12");
        String keytool = Path.of(System.getProperty("java.home"), "bin", "keytool").toString();
        Process p = new ProcessBuilder(keytool, "-genkeypair", "-alias", "server",
                "-keyalg", "EC", "-dname", "CN=localhost", "-ext", "SAN=dns:localhost",
                "-validity", "1", "-storetype", "PKCS12", "-keystore", keystore.toString(),
                "-storepass", PASSWORD).redirectErrorStream(true).start();
        p.getInputStream().readAllBytes();
        System.out.println("keytool exit code: " + p.waitFor());
        return keystore;
    }

    // Server side: KeyManagers hold our private key and certificate
    static SSLContext serverContext(KeyStore ks) throws Exception {
        String alg = KeyManagerFactory.getDefaultAlgorithm();
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(alg);
        kmf.init(ks, PASSWORD.toCharArray());
        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(kmf.getKeyManagers(), null, null);
        return ctx;
    }

    // Client side: TrustManagers decide which server certificates to accept
    static SSLContext clientContextTrusting(X509Certificate cert) throws Exception {
        KeyStore trust = KeyStore.getInstance("PKCS12");
        trust.load(null, null);
        trust.setCertificateEntry("server", cert);
        TrustManagerFactory tmf =
                TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(trust);
        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(null, tmf.getTrustManagers(), null);
        return ctx;
    }

    static void serveTwice(SSLServerSocket server) {
        for (int i = 0; i < 2; i++) {
            try (SSLSocket client = (SSLSocket) server.accept();
                 PrintWriter out = new PrintWriter(
                         client.getOutputStream(), true, StandardCharsets.UTF_8)) {
                out.println("hello over TLS");
            } catch (IOException e) {
                // the second client aborts the handshake, which is expected here
            }
        }
    }
}

Output:

Output
keytool exit code: 0
certificate: CN=localhost, key algorithm EC
handshake ok: TLSv1.3, TLS_AES_256_GCM_SHA384
server said: hello over TLS
default trust store: SSLHandshakeException, PKIX path building failed = true
  • keytool -genkeypair wrote a PKCS12 keystore holding the private key and a certificate with subject CN=localhost and a subject alternative name (SAN) for localhost. Modern clients check the SAN, not the CN.
  • The server's SSLContext was built from KeyManagerFactory; the first client's from a TrustManagerFactory over a trust store containing only that certificate. They negotiated TLS 1.3 with TLS_AES_256_GCM_SHA384 and exchanged a line of text.
  • The client with default trust failed with SSLHandshakeException and the famous "PKIX path building failed": no chain from the server's certificate to any trusted authority. The fix is to add the right CA certificate to a trust store and use it, never a TrustManager that accepts everything. Code that disables certificate checks "for testing" tends to reach production.

Hostname verification is not automatic on raw sockets

Trusting a certificate is only half the check: the certificate must also be for the host you meant to reach. The certificate here names only localhost. The client connects as localhost and as 127.0.0.1, with and without endpoint identification.

Java
import java.io.IOException;
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.SSLHandshakeException;
import javax.net.ssl.SSLParameters;
import javax.net.ssl.SSLServerSocket;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.TrustManagerFactory;

public class HostnameCheck {

    static final char[] PASSWORD = "changeit".toCharArray();

    public static void main(String[] args) throws Exception {
        KeyStore ks = keystore("CN=localhost", "SAN=dns:localhost");   // valid for "localhost"
        KeyManagerFactory kmf = KeyManagerFactory.getInstance("PKIX");
        kmf.init(ks, PASSWORD);
        SSLContext serverCtx = SSLContext.getInstance("TLS");
        serverCtx.init(kmf.getKeyManagers(), null, null);

        // The client trusts this exact certificate
        TrustManagerFactory tmf = TrustManagerFactory.getInstance("PKIX");
        tmf.init(ks);
        SSLContext clientCtx = SSLContext.getInstance("TLS");
        clientCtx.init(null, tmf.getTrustManagers(), null);

        try (SSLServerSocket server = (SSLServerSocket)
                serverCtx.getServerSocketFactory().createServerSocket(0)) {
            Thread t = new Thread(() -> acceptForever(server));
            t.setDaemon(true);
            t.start();
            int port = server.getLocalPort();
            System.out.println("1. 'localhost', no hostname check:  " + connect(clientCtx,
                    "localhost", port, false));
            System.out.println("2. '127.0.0.1', no hostname check:  " + connect(clientCtx,
                    "127.0.0.1", port, false) + "   <- accepted the wrong name");
            System.out.println("3. '127.0.0.1', HTTPS hostname check: " + connect(clientCtx,
                    "127.0.0.1", port, true));
            System.out.println("4. 'localhost', HTTPS hostname check: " + connect(clientCtx,
                    "localhost", port, true));
        }
    }

    static String connect(SSLContext ctx, String host, int port, boolean verifyHost) {
        try (SSLSocket s = (SSLSocket) ctx.getSocketFactory().createSocket(host, port)) {
            if (verifyHost) {
                SSLParameters p = s.getSSLParameters();
                p.setEndpointIdentificationAlgorithm("HTTPS");   // check name against the cert
                s.setSSLParameters(p);
            }
            s.startHandshake();
            return "handshake ok";
        } catch (SSLHandshakeException e) {
            return "SSLHandshakeException: " + e.getMessage();
        } catch (IOException e) {
            return e.toString();
        }
    }

    static void acceptForever(SSLServerSocket server) {
        while (true) {
            try (SSLSocket c = (SSLSocket) server.accept()) {
                c.startHandshake();
            } catch (IOException e) {
                if (server.isClosed()) {
                    return;
                }
            }
        }
    }

    static KeyStore keystore(String dname, String san) throws Exception {
        Path file = Files.createTempDirectory("tls").resolve("ks.p12");
        String keytool = Path.of(System.getProperty("java.home"), "bin", "keytool").toString();
        Process p = new ProcessBuilder(keytool, "-genkeypair", "-alias", "key", "-keyalg", "EC",
                "-dname", dname, "-ext", san, "-validity", "1", "-storetype", "PKCS12",
                "-keystore", file.toString(), "-storepass", "changeit")
                .redirectErrorStream(true).start();
        p.getInputStream().readAllBytes();
        p.waitFor();
        KeyStore ks = KeyStore.getInstance("PKCS12");
        try (InputStream in = Files.newInputStream(file)) {
            ks.load(in, PASSWORD);
        }
        return ks;
    }
}

Output:

Output
1. 'localhost', no hostname check:  handshake ok
2. '127.0.0.1', no hostname check:  handshake ok   <- accepted the wrong name
3. '127.0.0.1', HTTPS hostname check: SSLHandshakeException: (certificate_unknown) No subject alternative names matching IP address 127.0.0.1 found
4. 'localhost', HTTPS hostname check: handshake ok
  1. Connecting to localhost succeeded, as expected.
  2. Connecting to 127.0.0.1 also succeeded, although the certificate does not name that address. A plain SSLSocket checks the chain but not the name; any certificate from a trusted CA, issued for any site, would have been accepted.
  3. With setEndpointIdentificationAlgorithm("HTTPS") the same connection failed: "No subject alternative names matching IP address 127.0.0.1 found".
  4. With the check on and the right name, the handshake succeeded.

HttpClient and HttpsURLConnection verify the host name by default. Code that uses SSLSocket or SSLEngine directly, such as custom protocols, must turn it on itself. See SSL sockets for more socket-level TLS.

Mutual TLS: the client proves who it is

In ordinary TLS only the server has a certificate. In mutual TLS, common between internal services, the server also demands one from the client and checks it against its own trust store. The server below requires client authentication; one client presents a certificate for CN=billing-service and another presents none.

Java
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
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 final char[] PASSWORD = "changeit".toCharArray();

    public static void main(String[] args) throws Exception {
        KeyStore serverKeys = keystore("CN=localhost");
        KeyStore clientKeys = keystore("CN=billing-service");

        // Each side trusts the other's certificate
        KeyStore serverTrusts = trustStoreWith(clientKeys.getCertificate("key"));
        KeyStore clientTrusts = trustStoreWith(serverKeys.getCertificate("key"));
        SSLContext serverCtx = context(serverKeys, serverTrusts);
        SSLContext clientWithCert = context(clientKeys, clientTrusts);
        SSLContext clientWithoutCert = context(null, clientTrusts);

        try (SSLServerSocket server = (SSLServerSocket)
                serverCtx.getServerSocketFactory().createServerSocket(0)) {
            server.setNeedClientAuth(true);                 // mutual TLS: demand a certificate
            BlockingQueue<String> serverLog = new LinkedBlockingQueue<>();
            Thread t = new Thread(() -> {
                for (int i = 0; i < 2; i++) {
                    try (SSLSocket c = (SSLSocket) server.accept()) {
                        c.startHandshake();
                        serverLog.add("client is " + c.getSession().getPeerPrincipal().getName());
                    } catch (IOException e) {
                        serverLog.add("rejected a client: " + e.getClass().getSimpleName());
                    }
                }
            });
            t.start();
            int port = server.getLocalPort();
            System.out.println("client with a certificate:");
            System.out.println("  client: " + talk(clientWithCert, port));
            System.out.println("  server: " + serverLog.take());
            System.out.println("client without a certificate:");
            System.out.println("  client: " + talk(clientWithoutCert, port));
            System.out.println("  server: " + serverLog.take());
            t.join();
        }
    }

    static String talk(SSLContext ctx, int port) {
        try (SSLSocket s = (SSLSocket) ctx.getSocketFactory().createSocket("localhost", port)) {
            s.startHandshake();
            // In TLS 1.3 the server checks the client certificate after the client's side of
            // the handshake has finished, so a rejection shows up on the first read
            int b = s.getInputStream().read();
            return "handshake done, server closed the connection (read " + b + ")";
        } catch (IOException e) {
            return "failed: " + e.getClass().getSimpleName();
        }
    }

    static SSLContext context(KeyStore keys, KeyStore trust) throws Exception {
        KeyManagerFactory kmf = KeyManagerFactory.getInstance("PKIX");
        TrustManagerFactory tmf = TrustManagerFactory.getInstance("PKIX");
        tmf.init(trust);
        SSLContext ctx = SSLContext.getInstance("TLS");
        if (keys != null) {
            kmf.init(keys, PASSWORD);
            ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
        } else {
            ctx.init(null, tmf.getTrustManagers(), null);
        }
        return ctx;
    }

    static KeyStore trustStoreWith(Certificate cert) throws Exception {
        KeyStore ks = KeyStore.getInstance("PKCS12");
        ks.load(null, null);
        ks.setCertificateEntry("peer", cert);
        return ks;
    }

    static KeyStore keystore(String dname) throws Exception {
        Path file = Files.createTempDirectory("tls").resolve("ks.p12");
        String keytool = Path.of(System.getProperty("java.home"), "bin", "keytool").toString();
        Process p = new ProcessBuilder(keytool, "-genkeypair", "-alias", "key", "-keyalg", "EC",
                "-dname", dname, "-ext", "SAN=dns:localhost", "-validity", "1",
                "-storetype", "PKCS12", "-keystore", file.toString(), "-storepass", "changeit")
                .redirectErrorStream(true).start();
        p.getInputStream().readAllBytes();
        p.waitFor();
        KeyStore ks = KeyStore.getInstance("PKCS12");
        try (InputStream in = Files.newInputStream(file)) {
            ks.load(in, PASSWORD);
        }
        return ks;
    }
}

Output:

Output
client with a certificate:
  client: handshake done, server closed the connection (read -1)
  server: client is CN=billing-service
client without a certificate:
  client: failed: SSLHandshakeException
  server: rejected a client: SSLHandshakeException
  • With a certificate, the handshake completed and the server read the client's identity, CN=billing-service, from getPeerPrincipal(). That name can drive authorization, replacing API keys between services.
  • Without a certificate, both sides failed with SSLHandshakeException. setNeedClientAuth(true) makes the certificate mandatory; setWantClientAuth(true) would request it but continue without one.
  • In TLS 1.3 the client may finish its part of the handshake before the server has checked the client certificate, so a rejection can surface on the client's first read or write rather than in startHandshake(). The program reads from the socket for that reason.
  • Each side needs both managers here: KeyManagers for its own certificate and TrustManagers for the other side's. Mixing up the two stores is the most common mutual TLS configuration error.

Protocol negotiation and disabled protocols

Client and server each have a list of enabled protocols, and the handshake picks the highest one both support. The program tries four combinations of the two lists.

Java
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.KeyStore;
import java.util.List;
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 ProtocolNegotiation {

    static final char[] PASSWORD = "changeit".toCharArray();

    public static void main(String[] args) throws Exception {
        KeyStore ks = keystore();
        KeyManagerFactory kmf = KeyManagerFactory.getInstance("PKIX");
        kmf.init(ks, PASSWORD);
        TrustManagerFactory tmf = TrustManagerFactory.getInstance("PKIX");
        tmf.init(ks);
        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

        System.out.println("server [1.3, 1.2], client [1.3, 1.2]: "
                + handshake(ctx, List.of("TLSv1.3", "TLSv1.2"), List.of("TLSv1.3", "TLSv1.2")));
        System.out.println("server [1.3, 1.2], client [1.2]:      "
                + handshake(ctx, List.of("TLSv1.3", "TLSv1.2"), List.of("TLSv1.2")));
        System.out.println("server [1.3],      client [1.2]:      "
                + handshake(ctx, List.of("TLSv1.3"), List.of("TLSv1.2")));
        System.out.println("client asks for TLSv1.1 (disabled):  "
                + handshake(ctx, List.of("TLSv1.3", "TLSv1.2"), List.of("TLSv1.1")));
    }

    static String handshake(SSLContext ctx, List<String> serverProtocols,
            List<String> clientProtocols) throws Exception {
        try (SSLServerSocket server = (SSLServerSocket)
                ctx.getServerSocketFactory().createServerSocket(0)) {
            server.setEnabledProtocols(serverProtocols.toArray(String[]::new));
            Thread t = new Thread(() -> {
                try (SSLSocket c = (SSLSocket) server.accept()) {
                    c.startHandshake();
                } catch (IOException e) {
                    // the failure is reported by the client below
                }
            });
            t.start();
            try (SSLSocket s = (SSLSocket) ctx.getSocketFactory()
                    .createSocket("localhost", server.getLocalPort())) {
                s.setEnabledProtocols(clientProtocols.toArray(String[]::new));
                s.startHandshake();
                return s.getSession().getProtocol() + " with " + s.getSession().getCipherSuite();
            } catch (IOException e) {
                return e.getClass().getSimpleName() + ": " + e.getMessage();
            } finally {
                t.join();
            }
        }
    }

    static KeyStore keystore() throws Exception {
        Path file = Files.createTempDirectory("tls").resolve("ks.p12");
        String keytool = Path.of(System.getProperty("java.home"), "bin", "keytool").toString();
        Process p = new ProcessBuilder(keytool, "-genkeypair", "-alias", "key", "-keyalg", "EC",
                "-dname", "CN=localhost", "-ext", "SAN=dns:localhost", "-validity", "1",
                "-storetype", "PKCS12", "-keystore", file.toString(), "-storepass", "changeit")
                .redirectErrorStream(true).start();
        p.getInputStream().readAllBytes();
        p.waitFor();
        KeyStore ks = KeyStore.getInstance("PKCS12");
        try (InputStream in = Files.newInputStream(file)) {
            ks.load(in, PASSWORD);
        }
        return ks;
    }
}

Output:

Output
server [1.3, 1.2], client [1.3, 1.2]: TLSv1.3 with TLS_AES_256_GCM_SHA384
server [1.3, 1.2], client [1.2]:      TLSv1.2 with TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384
server [1.3],      client [1.2]:      SSLHandshakeException: (protocol_version) Received fatal alert: protocol_version
client asks for TLSv1.1 (disabled):  SSLHandshakeException: No appropriate protocol (protocol is disabled or cipher suites are inappropriate)
  • With both sides allowing TLS 1.3 and 1.2, they chose 1.3. With the client limited to 1.2, they used TLS 1.2 and a TLS 1.2 cipher suite with ECDHE key exchange and ECDSA authentication, matching the EC certificate.
  • A server that allows only 1.3 and a client that allows only 1.2 have nothing in common, and the server answered with a protocol_version alert.
  • Asking for TLS 1.1 failed before anything was sent: "No appropriate protocol". The protocol is disabled by jdk.tls.disabledAlgorithms, and setEnabledProtocols cannot override that. Re-enabling it means editing the security property, which should be a temporary measure for talking to a legacy system.
  • For debugging any handshake failure, run with -Djavax.net.debug=ssl:handshake, which prints every handshake message, the certificates and the negotiated parameters.

Common TLS errors and what to do

TLS error messages in Java
ErrorCauseFix
PKIX path building failedThe trust store has no CA for the server's chain, or the server sends an incomplete chainImport the CA into a trust store; make the server send intermediates
No subject alternative names matching ...The certificate does not name the host or IP usedConnect with the name in the certificate, or reissue it with the right SAN
protocol_version or No appropriate protocolNo common enabled protocolUpgrade the old side; enable TLS 1.2 or 1.3
handshake_failureNo common cipher suite, or a missing client certificateCompare the enabled suites; check client authentication settings
certificate_expired / NotAfterThe certificate's validity period has passedRenew it, and monitor expiry dates

Useful keytool commands: keytool -list -v -keystore ks.p12 shows entries and validity, keytool -importcert -alias ca -file ca.pem -keystore trust.p12 adds a trusted CA, and keytool -printcert -sslserver host:443 shows the chain a server actually sends.

Choosing the right setup

Security and TLS recipes
NeedUse
Call HTTPS servicesHttpClient with the default SSLContext; a custom one only for private CAs
Trust a private CAA PKCS12 trust store with that CA, passed to TrustManagerFactory
Serve TLSA PKCS12 keystore with key and full chain, passed to KeyManagerFactory
Raw SSLSocket or SSLEngine clientsAlways set endpoint identification to "HTTPS"
Service-to-service authenticationMutual TLS with setNeedClientAuth(true)
Hashing, encryption, signaturesThe crypto pages: digests, AES, RSA
PasswordsPBKDF2 with a random salt, never a plain digest
Message authenticationHMAC

For HTTP specifics, see HttpClient in depth.