How to fix "SSLHandshakeException" when using Spring RestTemplate with self signed certificate


Bhdr

I'm trying to call a REST Api (https, secured with a self-signed certificate) with a Java client using Spring's RestTemplate. When I try to use Postman, it succeeds. I have a crt file and a private key file. I have them defined in postman settings/certificates and the request is successful. However, when I try to use the Java code, I get an SSLHandshakeException.

I am using Java 11 and Spring Boot. I created a .jks file using keytool and put it in the classpath. The keytool command I use is:

keytool-导入-alias别名-file blahblah.crt -keypass keypass -keystore mykeystore.jks -storepass mystorepass

(I thought I couldn't use the .crt certificate file directly, so I created the .jks file)

Then I run the following code:

URL storeUrl = new URL("classpath:mykeystore.jks");
SSLContext sslContext = new SSLContextBuilder()
                    .setProtocol("TLSv1.2")                    
                    .loadTrustMaterial(new TrustSelfSignedStrategy())
                    .loadKeyMaterial(storeUrl, trustStorePassword.toCharArray(), keyPassword.toCharArray())
                    .build();
            SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext);
            HttpClient httpClient = HttpClients.custom()
                    .setSSLSocketFactory(socketFactory)
                    .build();
            HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient);
            restTemplate = new RestTemplate(factory);

//...
restTemplate.postForObject(myUri, new HttpEntity<>(json, httpHeaders), String.class);

The console output is:


javax.net.ssl|DEBUG|18|http-nio-8080-exec-2|2019-08-08 15:59:18.548 EEST|HandshakeContext.java:290|Ignore unsupported cipher suite: TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 for TLS11
javax.net.ssl|DEBUG|18|http-nio-8080-exec-2|2019-08-08 15:59:18.548 EEST|HandshakeContext.java:290|Ignore unsupported cipher suite: TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 for TLS11
javax.net.ssl|DEBUG|18|http-nio-8080-exec-2|2019-08-08 15:59:18.548 EEST|HandshakeContext.java:290|Ignore unsupported cipher suite: TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 for TLS11
...
javax.net.ssl|WARNING|18|http-nio-8080-exec-2|2019-08-08 15:59:18.577 EEST|SignatureScheme.java:282|Signature algorithm, ed25519, is not supported by the underlying providers
javax.net.ssl|WARNING|18|http-nio-8080-exec-2|2019-08-08 15:59:18.578 EEST|SignatureScheme.java:282|Signature algorithm, ed448, is not supported by the underlying providers
javax.net.ssl|ALL|18|http-nio-8080-exec-2|2019-08-08 15:59:18.584 EEST|SignatureScheme.java:358|Ignore disabled signature sheme: rsa_md5
javax.net.ssl|INFO|18|http-nio-8080-exec-2|2019-08-08 15:59:18.585 EEST|AlpnExtension.java:161|No available application protocols
javax.net.ssl|DEBUG|18|http-nio-8080-exec-2|2019-08-08 15:59:18.585 EEST|SSLExtensions.java:256|Ignore, context unavailable extension: application_layer_protocol_negotiation
javax.net.ssl|DEBUG|18|http-nio-8080-exec-2|2019-08-08 15:59:18.586 EEST|SSLExtensions.java:256|Ignore, context unavailable extension: renegotiation_info
javax.net.ssl|DEBUG|18|http-nio-8080-exec-2|2019-08-08 15:59:18.588 EEST|ClientHello.java:651|Produced ClientHello handshake message (
"ClientHello": {
  "client version"      : "TLSv1.2",
  "random"              : "A2 04 D2 4A 94 06 0D 4B 8A ....",
  "session id"          : "",
  "cipher suites"       : "[TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384(0xC02C), TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256(0xC02B), TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384(0xC030), TLS_RSA_WITH_AES_256_GCM_SHA384(0x009D), TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384(0xC02E), TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384(0xC032), TLS_DHE_RSA_WITH_AES_256_GCM_SHA384(0x009F), TLS_DHE_DSS_WITH_AES_256_GCM_SHA384(0x00A3), TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256(0xC02F), TLS_RSA_WITH_AES_128_GCM_SHA256(0x009C), TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256(0xC02D), TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256(0xC031), TLS_DHE_RSA_WITH_AES_128_GCM_SHA256(0x009E), TLS_DHE_DSS_WITH_AES_128_GCM_SHA256(0x00A2), TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384(0xC024), TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384(0xC028), TLS_RSA_WITH_AES_256_CBC_SHA256(0x003D), TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384(0xC026), TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384(0xC02A), TLS_DHE_RSA_WITH_AES_256_CBC_SHA256(0x006B), TLS_DHE_DSS_WITH_AES_256_CBC_SHA256(0x006A), TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA(0xC00A), TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA(0xC014), TLS_RSA_WITH_AES_256_CBC_SHA(0x0035), TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA(0xC005), TLS_ECDH_RSA_WITH_AES_256_CBC_SHA(0xC00F), TLS_DHE_RSA_WITH_AES_256_CBC_SHA(0x0039), TLS_DHE_DSS_WITH_AES_256_CBC_SHA(0x0038), TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256(0xC023), TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256(0xC027), TLS_RSA_WITH_AES_128_CBC_SHA256(0x003C), TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256(0xC025), TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256(0xC029), TLS_DHE_RSA_WITH_AES_128_CBC_SHA256(0x0067), TLS_DHE_DSS_WITH_AES_128_CBC_SHA256(0x0040), TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA(0xC009), TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA(0xC013), TLS_RSA_WITH_AES_128_CBC_SHA(0x002F), TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA(0xC004), TLS_ECDH_RSA_WITH_AES_128_CBC_SHA(0xC00E), TLS_DHE_RSA_WITH_AES_128_CBC_SHA(0x0033), TLS_DHE_DSS_WITH_AES_128_CBC_SHA(0x0032), TLS_EMPTY_RENEGOTIATION_INFO_SCSV(0x00FF)]",
  "compression methods" : "00",
  "extensions"          : [
    "server_name (0)": {
      type=host_name (0), value=
    },
    "status_request (5)": {
      "certificate status type": ocsp
      "OCSP status request": {
        "responder_id": <empty>
        "request extensions": {
          <empty>
        }
      }
    },
    "supported_versions (43)": {
      "versions": [TLSv1.2, TLSv1.1, TLSv1]
    }
  ]
}
)
javax.net.ssl|DEBUG|18|http-nio-8080-exec-2|2019-08-08 15:59:18.653 EEST|ServerHello.java:884|Consuming ServerHello handshake message (
"ServerHello": {
  "server version"      : "TLSv1.2",
  "random"              : "1A 57 59 ",
  "session id"          : "",
  "cipher suite"        : "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384(0xC030)",
  "compression methods" : "00",
  "extensions"          : [
    "renegotiation_info (65,281)": {
      "renegotiated connection": [<no renegotiated connection>]
    },
    "ec_point_formats (11)": {
      "formats": [uncompressed, ansiX962_compressed_prime, ansiX962_compressed_char2]
    }
  ]
}
)
javax.net.ssl|DEBUG|18|http-nio-8080-exec-2|2019-08-08 15:59:18.653 EEST|SSLExtensions.java:169|Ignore unavailable extension: supported_versions
javax.net.ssl|DEBUG|18|http-nio-8080-exec-2|2019-08-08 15:59:18.654 EEST|ServerHello.java:980|Negotiated protocol version: TLSv1.2
javax.net.ssl|DEBUG|18|http-nio-8080-exec-2|2019-08-08 15:59:18.654 EEST|SSLExtensions.java:188|Consumed extension: renegotiation_info
javax.net.ssl|DEBUG|18|http-nio-8080-exec-2|2019-08-08 15:59:18.654 EEST|SSLExtensions.java:169|Ignore unavailable extension: server_name
javax.net.ssl|DEBUG|18|http-nio-8080-exec-2|2019-08-08 15:59:18.654 EEST|SSLExtensions.java:169|Ignore unavailable extension: max_fragment_length
javax.net.ssl|DEBUG|18|http-nio-8080-exec-2|2019-08-08 15:59:18.654 EEST|SSLExtensions.java:169|Ignore unavailable extension: status_request
javax.net.ssl|WARNING|18|http-nio-8080-exec-2|2019-08-08 15:59:18.655 EEST|SSLExtensions.java:211|Ignore impact of unsupported extension: ec_point_formats

javax.net.ssl|DEBUG|18|http-nio-8080-exec-2|2019-08-08 15:59:18.658 EEST|CertificateMessage.java:358|Consuming server Certificate handshake message (
"Certificates": [
  "certificate" : {
    "version"            : "v1",
    "serial number"      : "00 BE F3 ...",
    "signature algorithm": "SHA256withRSA",
    "issuer"             : "CN=, O=, L=, C=AT",
    "not before"         : "2019-07-11 10:29:05.000 EEST",
    "not  after"         : "2020-07-10 10:29:05.000 EEST",
    "subject"            : "CN=, O=, L=, C=AT",
    "subject public key" : "RSA"}
]
)
javax.net.ssl|DEBUG|18|http-nio-8080-exec-2|2019-08-08 15:59:18.673 EEST|ECDHServerKeyExchange.java:538|Consuming ECDH ServerKeyExchange handshake message (
"ECDH ServerKeyExchange": {
  "parameters": {
    "named group": "secp256r1"
    "ecdh public": {
      0000: 04 01 D4 17 80 61 6E BD   7B C1 A1 C4 E5 21 94 30  .....an......!.0
      ...
    },
  },
  "digital signature":  {
    "signature algorithm": "rsa_pkcs1_sha256"
    "signature": {
    ...
    },
javax.net.ssl|DEBUG|18|http-nio-8080-exec-2|2019-08-08 15:59:18.675 EEST|CertificateRequest.java:651|Consuming CertificateRequest handshake message (
"CertificateRequest": {
  "certificate types": [rsa_sign, dss_sign, ecdsa_sign]
  "supported signature algorithms": [rsa_pkcs1_sha512, dsa_sha512, ecdsa_secp512r1_sha512, rsa_pkcs1_sha384, dsa_sha384, ecdsa_secp384r1_sha384, rsa_pkcs1_sha256, dsa_sha256, ecdsa_secp256r1_sha256, rsa_sha224, dsa_sha224, ecdsa_sha224, rsa_pkcs1_sha1, dsa_sha1, ecdsa_sha1]
  "certificate authorities": [CN=*.mysugr.com, O=mySugr GmbH, L=Vienna, C=AT]
}
)
javax.net.ssl|WARNING|18|http-nio-8080-exec-2|2019-08-08 15:59:18.675 EEST|CertificateRequest.java:691|No available client authentication
javax.net.ssl|DEBUG|18|http-nio-8080-exec-2|2019-08-08 15:59:18.676 EEST|ServerHelloDone.java:142|Consuming ServerHelloDone handshake message (
<empty>
)
javax.net.ssl|DEBUG|18|http-nio-8080-exec-2|2019-08-08 15:59:18.676 EEST|CertificateMessage.java:291|No X.509 certificate for client authentication, use empty Certificate message instead
javax.net.ssl|DEBUG|18|http-nio-8080-exec-2|2019-08-08 15:59:18.676 EEST|CertificateMessage.java:322|Produced client Certificate handshake message (
"Certificates": <empty list>
)
javax.net.ssl|DEBUG|18|http-nio-8080-exec-2|2019-08-08 15:59:18.681 EEST|ECDHClientKeyExchange.java:401|Produced ECDHE ClientKeyExchange handshake message (
"ECDH ClientKeyExchange": {
  "ecdh public": {
    0000: 04 30 F6 65 48 8F 99 BB   71 C7 70 4F E4 82 52 3A  .0.eH...q.pO..R:
    ...
  },
}
)
javax.net.ssl|DEBUG|18|http-nio-8080-exec-2|2019-08-08 15:59:18.691 EEST|ChangeCipherSpec.java:117|Produced ChangeCipherSpec message
javax.net.ssl|DEBUG|18|http-nio-8080-exec-2|2019-08-08 15:59:18.692 EEST|Finished.java:395|Produced client Finished handshake message (
"Finished": {
  "verify data": {
    0000: 80 B1 ...
  }'}
)
javax.net.ssl|DEBUG|18|http-nio-8080-exec-2|2019-08-08 15:59:18.731 EEST|Alert.java:232|Received alert message (
"Alert": {
  "level"      : "fatal",
  "description": "handshake_failure"
}
)
javax.net.ssl|ERROR|18|http-nio-8080-exec-2|2019-08-08 15:59:18.733 EEST|TransportContext.java:313|Fatal (HANDSHAKE_FAILURE): Received fatal alert: handshake_failure (
"throwable" : {
  javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure

I've been trying to fix for 2 days and still can't find a solution. Is there something I can't see, or is it possible to understand why the handshake fails? thank you very much.

Bhdr

I'll answer my own question: yes, we need to create a .jks file from a .crt file. Then, the Java code is:

try {
            RestTemplate restTemplate = new RestTemplate();

            KeyStore keyStore = KeyStore.getInstance("jks");

            File keyFile = new File(KEY_STORE_FILE);
            FileSystemResource fileSystemResource = new FileSystemResource(keyFile);

            InputStream inputStream = fileSystemResource.getInputStream();
            keyStore.load(inputStream,
                    Objects.requireNonNull(KEY_STORE_PASS).toCharArray());

            SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(new SSLContextBuilder()
                    .loadTrustMaterial(null, new TrustSelfSignedStrategy())
                    .loadKeyMaterial(keyStore,
                            KEY_PASS.toCharArray()).build(),
                    NoopHostnameVerifier.INSTANCE);

            HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory)
                    .build();

            HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);

            restTemplate.setRequestFactory(requestFactory);

            return restTemplate;

        } catch (Exception e) {
            logger.debug("SSL keystore exception", e);
            throw new BlahBlahException(e);
        }



Related


How to respond to OCSPRequest when using self-signed certificate?

Freddie Muskelberg I'm trying to create an https server with a self-signed certificate, but it seems to be failing because it requires a response to the OCSPRequestcallback , which I don't know what to include. The documentation ( https://nodejs.org/api/tls.ht

Self signed certificate in spring boot

j I'm trying to get a Spring-Boot server up and running, which provides some security over SSL. I followed steps 1 and 2 of this guide to get a self-signed certificate and was able to access my website via . This looks like this:httpsapplication.properties ser

Self signed certificate in spring boot

j I'm trying to get a Spring-Boot server up and running, which provides some security over SSL. I followed steps 1 and 2 of this guide to get a self-signed certificate and was able to access my website via . This looks like this:httpsapplication.properties ser

Self signed certificate in spring boot

j I'm trying to get a Spring-Boot server up and running, which provides some security over SSL. I followed steps 1 and 2 of this guide to get a self-signed certificate and was able to access my website via . This looks like this:httpsapplication.properties ser

Self signed certificate in spring boot

j I'm trying to get a Spring-Boot server up and running, which provides some security over SSL. I followed steps 1 and 2 of this guide to get a self-signed certificate and was able to access my website via . This looks like this:httpsapplication.properties ser

Self signed certificate in spring boot

j I'm trying to get a Spring-Boot server up and running, which provides some security over SSL. I followed steps 1 and 2 of this guide to get a self-signed certificate and was able to access my website via . This looks like this:httpsapplication.properties ser

Self signed certificate in spring boot

j I'm trying to get a Spring-Boot server up and running, which provides some security over SSL. I followed steps 1 and 2 of this guide to get a self-signed certificate and was able to access my website via . This looks like this:httpsapplication.properties ser

How to avoid browser warnings when self-signed SSL certificate?

Stephan Ahlf I plan to deploy my own hardware device in the form of a RaspberryPi running a NodeJs server, which should include HTTPS communication. It is intended to run as an intranet device and will always be named with the same computer name (or the same I

How to avoid browser warnings when self-signed SSL certificate?

Stephan Ahlf I plan to deploy my own hardware device in the form of a RaspberryPi running a NodeJs server, which should include HTTPS communication. It is intended to run as an intranet device and will always be named with the same computer name (or the same I

How to avoid browser warnings when self-signed SSL certificate?

Stephan Ahlf I plan to deploy my own hardware device in the form of a RaspberryPi running a NodeJs server, which should include HTTPS communication. It is intended to run as an intranet device and will always be named with the same computer name (or the same I

How to avoid browser warnings when self-signed SSL certificate?

Stephan Ahlf I plan to deploy my own hardware device in the form of a RaspberryPi running a NodeJs server, which should include HTTPS communication. It is intended to run as an intranet device and will always be named with the same computer name (or the same I

How to avoid browser warnings when self-signed SSL certificate?

Stephan Ahlf I plan to deploy my own hardware device in the form of a RaspberryPi running a NodeJs server, which should include HTTPS communication. It is intended to run as an intranet device and will always be named with the same computer name (or the same I