使用带有自签名证书的 Spring RestTemplate 时如何修复 "SSLHandshakeException"

How to fix "SSLHandshakeException" while using Spring RestTemplate with a self-signed certificate

我正在尝试使用 Spring 的 RestTemplate 通过 Java 客户端调用 REST Api(https,使用自签名证书保护)。当我尝试使用 Postman 时,它是成功的。我有一个crt文件和一个私钥文件。我在 Postman settings/certificates 中定义它们并且请求成功。但是当我尝试使用 Java 代码时,我得到 SSLHandshakeException。

我正在使用 Java 11 和 Spring Boot。我使用 keytool 创建了一个 .jks 文件并将其放在类路径中。我使用的keytool命令是:

keytool -import -alias alias -file blahblah.crt -keypass keypass -keystore mykeystore.jks -storepass mystorepass

(我估计不能直接使用.crt证书文件,所以我创建了一个.jks文件)

然后我运行下面的代码:

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);

控制台输出为:


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

我已经尝试解决这个问题 2 天了,但仍然找不到解决方案。有什么我看不到的,或者是否有可能了解握手失败的原因?非常感谢。

我会回答我自己的问题:是的,我们需要从 .crt 文件创建一个 .jks 文件。然后 Java 代码是:

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);
        }