我编写了一个模块,通过身份验证通过 https 连接到服务。设置正确的 keystore 路径后,它工作正常。当我想在我的 Tomcat 应用程序中使用该模块(作为 jar)时出现问题。我也为 keystore 设置了正确的路径(绝对路径)但是当我尝试连接时出现握手异常
PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
我记得我之前收到此消息是因为我的 keystore 不正确。我需要做更多的事情才能让它在 Tomcat 下工作吗?我错过了任何其他问题吗? 我在没有身份验证的情况下通过 https 连接到另一个服务,这工作正常(在 Tomcat 应用程序中)。
编辑:问题是运行一个通过 ssl 连接到不同服务的项目(不仅在 Tomcat 中)。一个有身份验证,第二个没有。所以我编辑了标题
最佳答案
Setting multiple truststore on the same JVM给了我一个答案。我只需要设置我的 key 工厂和信任工厂就可以了:)
System.setProperty 不设置已设置的 ssl 属性。
// load your key store as a stream and initialize a KeyStore
InputStream trustStream = new FileInputStream("Resources/keystore.ImportKey");
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
// if your store is password protected then declare it (it can be null however)
String trustPassword = "changeit";
// load the stream to your store
trustStore.load(trustStream, trustPassword.toCharArray());
// initialize a trust manager factory with the trusted store
TrustManagerFactory trustFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustFactory.init(trustStore);
KeyManagerFactory keyFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyFactory.init(trustStore, trustPassword.toCharArray());
// get the trust managers from the factory
TrustManager[] trustManagers = trustFactory.getTrustManagers();
KeyManager[] keyManagers = keyFactory.getKeyManagers();
// initialize an ssl context to use these managers and set as default
SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(keyManagers, trustManagers, null);
SSLContext.setDefault(sslContext);
一切正常!
关于java - 多个 ssl 连接时的 SSLHandshakeException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9976798/