一尘不染

为什么找不到SSL握手的信任库?

tomcat

我在客户端使用Spring RESTTemplate来调用REST端点。在这种情况下,客户端是Spring应用程序,而Tomcat是servlet容器。

我在与HTTPS端点建立连接时遇到问题。我收到一条错误消息,指示它无法找到信任库的有效路径。我在哪里可以指定?这是在容器级别还是在应用程序配置(Spring)级别完成的?

堆栈跟踪:

org.springframework.web.client.ResourceAccessException: I/O error:
sun.security.validator.ValidatorException: PKIX path building failed:
sun.security.provider.certpath.SunCertPathBuilderException:
unable to find valid certification path to requested target;
nested exception is 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
org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:330)
org.springframework.web.client.RestTemplate.execute(RestTemplate.java:292)
org.springframework.web.client.RestTemplate.postForObject(RestTemplate.java:227)

阅读 313

收藏
2020-06-16

共1个答案

一尘不染

您需要正确配置在RESTTemplate外部完成的SSLContext。这应该使您开始:

    String keystoreType = "JKS";
    InputStream keystoreLocation = null;
    char [] keystorePassword = null;
    char [] keyPassword = null;

    KeyStore keystore = KeyStore.getInstance(keystoreType);
    keystore.load(keystoreLocation, keystorePassword);
    KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmfactory.init(keystore, keyPassword);

    InputStream truststoreLocation = null;
    char [] truststorePassword = null;
    String truststoreType = "JKS";

    KeyStore truststore = KeyStore.getInstance(truststoreType);
    truststore.load(truststoreLocation, truststorePassword);
    TrustManagerFactory tmfactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());

    KeyManager [] keymanagers = kmfactory.getKeyManagers();
    TrustManager [] trustmanagers =  tmfactory.getTrustManagers();

    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(keymanagers, trustmanagers, new SecureRandom());
    SSLContext.setDefault(sslContext);
2020-06-16