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 Providers, algorithms and TLS defaults A TLS server and client in one program Hostname verification is not automatic on raw sockets Mutual TLS: the client proves who it is Protocol negotiation and disabled protocols Common TLS errors and what to do Choosing the right setup
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")
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
- KeyManagers hold your own private key and certificate, read from a
. A server always needs them; a client needs them only for mutual TLS.KeyStore - 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
| Piece | Since | Notes |
|---|---|---|
JCA providers, MessageDigestSignature | Java 1.1 | Algorithms by name, implementations pluggable |
JCE: CipherMacKeyAgreement | Java 1.4 (bundled) | Encryption; see the crypto pages |
JSSE: SSLContextSSLSocketSSLEngine | Java 1.4 (bundled) | TLS for sockets and non-blocking I/O |
| PKCS12 as the default keystore type | Java 9 (JEP 229) | Replaced the Java-only JKS format |
| TLS 1.3 | Java 11 (JEP 332) | Faster handshake, only modern cipher suites |
| TLS 1.0 and 1.1 disabled by default | Java 16, also in later 8 and 11 updates | Listed in jdk.tls.disabledAlgorithms |
| Security Manager deprecated, then disabled | Deprecated 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 keytoollocalhost
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.
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:
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;
returns the implementation of the first one that supports the algorithm. SHA-256 came from SUN and AES/GCM from SunJCE.getInstance or theSecurity.insertProviderAt entries insecurity.provider.N change the order.java.security - SHA3-256 (Java 9) and MD5 are available; BLAKE2b is not in the JDK, so
threwgetInstance . 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.NoSuchAlgorithmException - The default TLS protocols are TLS 1.3 and 1.2, and the first cipher suites are the three TLS 1.3 suites.
, a security property injdk.tls.disabledAlgorithms , starts with SSLv3 and TLSv1, which is why old protocols fail even if code asks for them.conf/security/java.security
A TLS server and client in one program
keytoollocalhost
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:
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
wrote a PKCS12 keystore holding the private key and a certificate with subjectkeytool -genkeypair and a subject alternative name (SAN) forCN=localhost . Modern clients check the SAN, not the CN.localhost- The server's
was built fromSSLContext ; the first client's from aKeyManagerFactory over a trust store containing only that certificate. They negotiated TLS 1.3 withTrustManagerFactory and exchanged a line of text.TLS_AES_256_GCM_SHA384 - The client with default trust failed with
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.SSLHandshakeException
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 localhostlocalhost127.0.0.1
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:
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
- Connecting to
succeeded, as expected.localhost - Connecting to
also succeeded, although the certificate does not name that address. A plain127.0.0.1 checks the chain but not the name; any certificate from a trusted CA, issued for any site, would have been accepted.SSLSocket - With
the same connection failed: "No subject alternative names matching IP address 127.0.0.1 found".setEndpointIdentificationAlgorithm("HTTPS") - With the check on and the right name, the handshake succeeded.
HttpClientHttpsURLConnectionSSLSocketSSLEngine
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
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:
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,
, fromCN=billing-service . That name can drive authorization, replacing API keys between services.getPeerPrincipal() - Without a certificate, both sides failed with
.SSLHandshakeException makes the certificate mandatory;setNeedClientAuth(true) would request it but continue without one.setWantClientAuth(true) - 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
. The program reads from the socket for that reason.startHandshake() - 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.
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:
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
alert.protocol_version - Asking for TLS 1.1 failed before anything was sent: "No appropriate protocol". The protocol is disabled by
, andjdk.tls.disabledAlgorithms cannot override that. Re-enabling it means editing the security property, which should be a temporary measure for talking to a legacy system.setEnabledProtocols - For debugging any handshake failure, run with
, which prints every handshake message, the certificates and the negotiated parameters.-Djavax.net.debug=ssl:handshake
Common TLS errors and what to do
| Error | Cause | Fix |
|---|---|---|
| PKIX path building failed | The trust store has no CA for the server's chain, or the server sends an incomplete chain | Import 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 used | Connect with the name in the certificate, or reissue it with the right SAN |
| protocol_version or No appropriate protocol | No common enabled protocol | Upgrade the old side; enable TLS 1.2 or 1.3 |
| handshake_failure | No common cipher suite, or a missing client certificate | Compare the enabled suites; check client authentication settings |
| certificate_expired / NotAfter | The certificate's validity period has passed | Renew it, and monitor expiry dates |
Useful keytoolkeytool -list -v -keystore ks.p12keytool -importcert -alias ca -file ca.pem -keystore trust.p12keytool -printcert -sslserver host:443
Choosing the right setup
| Need | Use |
|---|---|
| Call HTTPS services | HttpClientSSLContext |
| Trust a private CA | A PKCS12 trust store with that CA, passed to TrustManagerFactory |
| Serve TLS | A PKCS12 keystore with key and full chain, passed to KeyManagerFactory |
Raw SSLSocketSSLEngine | Always set endpoint identification to "HTTPS" |
| Service-to-service authentication | Mutual TLS with setNeedClientAuth(true) |
| Hashing, encryption, signatures | The crypto pages: |
| Passwords | |
| Message authentication |
For HTTP specifics, see