Configure a Java HTTP Client to Accept Self-Signed Certificates

From NovaOrdis Knowledge Base
Jump to navigation Jump to search

Internal

Overview

If a Java client is attempting to connect to a HTTPS server configured with a self-signed SSL certificate, the Java client will fail with:

...
javax.net.ssl.SSLHandshakeException: \
sun.security.validator.ValidatorException: PKIX path building failed: \
sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

This article provides a solution to this problem. The solution consist in obtaining the HTTPS server's public key, importing it into a local truststore and configuring the Java client to use the local truststore.

Procedure

Obtain the HTTPS Server's Certificate

Use openssl s_client to obtain the server's certificate as described here. The response will include the server's certificate in PEM format, which should look similarly to:

-----BEGIN CERTIFICATE-----
MIIDqjCCAxOgAwIBAgIBADANBgkqhkiG9w0BAQQFADCBmzELMAkGA1UEBhMCVVMx
EzARBgNVBAgTCkNhbGlmb3JuaWExFDASBgNVBAcTC1NhbnRhIENsYXJhMRowGAYD
VQQKExEzREdlbyBEZXZlbG9wbWVudDEMMAoGA1UECxQDUiZEMRgwFgYDVQQDEw9k
ZWx0YS4zZGdlby5jb20xHTAbBgkqhkiG9w0BCQEWDnJvb3RAM2RnZW8uY29tMB4X
DTA3MDMxMzAwMDA1MVoXDTEyMDMxMTAwMDA1MVowgZsxCzAJBgNVBAYTAlVTMRMw
EQYDVQQIEwpDYWxpZm9ybmlhMRQwEgYDVQQHEwtTYW50YSBDbGFyYTEaMBgGA1UE
ChMRM0RHZW8gRGV2ZWxvcG1lbnQxDDAKBgNVBAsUA1ImRDEYMBYGA1UEAxMPZGVs
dGEuM2RnZW8uY29tMR0wGwYJKoZIhvcNAQkBFg5yb290QDNkZ2VvLmNvbTCBnzAN
BgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA0Qr+rQFlXbb6Cno44THzb7FqS2RM1839
v/PEU5dg4Ct5Lru57r9DE3ZYeTqhvKKJoBU7CpubCWdkmiH8VioTz0wg3cWOT/NL
1S0SBMHpUo5L7NlNDVs7BYb8Ul6Zw3TJOEv5k1/WaM6zCSmW3lp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