Calling webservice with SSL context ends up with: PKIX path building failed: unable to find valid certification path to requested target

50 views Asked by At

I'm running Spring Boot application with some simple REST services. In one of them I need to make a request to external webservice, which requires TLS. Cert file and key file for TLS communication were obtained.

Cert file was added into new empty truststore (trust-store.jks). I also created new empty keystore (key-store.jks) and I imported keypair - the same cert file and key.

Key-store and trust-store were added into project resources folder.

Then, while calling external service I'm creating SSL context like this (CustomConfig contains path to keystores on classpath and passwords):

public SslContext createSslContext(CustomConfig customConfig) {
    try {
          
      var keyStore = KeyStore.getInstance("PKCS12");
      try (var keyStoreStream = new ClassPathResource(customConfig.getKeyStore().getStore()).getInputStream()) {
        keyStore.load(keyStoreStream, customConfig.getKeyStore().getPassword().toCharArray());
      }

      var keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
      keyManagerFactory.init(keyStore, customConfig.getKeyStore().getPassword().toCharArray());

      var trustStore = KeyStore.getInstance("PKCS12");
      try (var trustStoreStream = new ClassPathResource(customConfig.getTrustStore().getStore()).getInputStream()) {
        trustStore.load(trustStoreStream, customConfig.getTrustStore().getPassword().toCharArray());
      }

      var trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
      trustManagerFactory.init(trustStore);

      return SslContextBuilder.forClient()
          .keyManager(keyManagerFactory)
          .trustManager(trustManagerFactory)
          .build();
    } catch (IOException | GeneralSecurityException e) {
      throw new SslContextException("Failed to create SSL context: " + e.getMessage());
    }
}

SSL context is built without any issue, but while http client trying to create connection this error occures:

Error: 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: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

Obtained cert and key file are valid, and I'm able to call external webservice with curl and those files.

Any suggestions, what I'm missing here?

0

There are 0 answers