Home โบ Java exceptions โบ SSLHandshakeException
SSLHandshakeException: causes and fixes
The TLS handshake failed: untrusted certificate, wrong host name, expired certificate or no shared protocol.
What it looks like
javax.net.ssl.SSLHandshakeException: PKIX path building failed: unable to find valid certification path to requested targetExtends SSLException in javax.net.ssl.
What it means
During the TLS handshake the client checks the server's certificate chain. "PKIX path building failed" means the chain does not lead to a certificate authority in the JVM's truststore: typical for self-signed or internal CA certificates. "No subject alternative names matching" means the certificate is valid but not for the host you used. "Received fatal alert: handshake_failure" means the two sides share no protocol or cipher suite.
Common causes
- A private or self-signed CA that is not in the Java truststore (cacerts).
- A server that does not send the intermediate certificate, so the chain cannot be built.
- An expired certificate, or the wrong host name or IP in the URL.
- Old TLS versions or ciphers disabled in the JVM, or a corporate proxy that re-signs traffic.
How to fix it
- Import the CA into a truststore and point to it with
-Djavax.net.ssl.trustStore=..., or add it to cacerts with keytool. - Fix the server to send the full chain and to use a certificate matching its host name.
- Inspect the certificate with
openssl s_client -connect host:443 -showcerts. - Do not disable certificate validation in production; that removes the protection TLS gives you.
Broken and fixed
// "fix" that disables verification: never ship this
SSLContext ctx = trustAllContext();keytool -importcert -alias internal-ca -file ca.pem \
-keystore truststore.p12 -storepass changeit
-Djavax.net.ssl.trustStore=truststore.p12๐ Unravel the failing code ๐ Unravel the fix
Debug it faster
Paste the whole stack trace into the stack trace beautifier to hide framework frames, jump to the root cause and find the first line of your own code. It runs in your browser, so the trace never leaves your machine.
Frequently asked questions
Is SSLHandshakeException a checked or unchecked exception?
SSLHandshakeException is a checked exception (it extends SSLException), so the compiler forces you to catch it or declare it with throws.
Which package is SSLHandshakeException in?
It lives in javax.net.ssl, so the import is import javax.net.ssl.SSLHandshakeException;.
What is the first thing to check when I see SSLHandshakeException?
Read the message and the first stack trace line in your own code. The usual causes are: A private or self-signed CA that is not in the Java truststore (cacerts); and A server that does not send the intermediate certificate, so the chain cannot be built.