我正在尝试以编程方式连接到安全的Web服务器。我有用于访问服务器的pfx证书,可以通过浏览器访问它。但是我收到以下错误:
java.security.cert.CertificateException:没有主题替代名称
我正在使用此代码:
KeyStore keyStore = KeyStore.getInstance("PKCS12");
keyStore.load(new FileInputStream("path/to/pfxFile"), "mypassword");
KeyManagerFactory keyManagerFactory = KeyManagerFactory
.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(keyStore, "mypassword");
KeyStore trustStore = KeyStore.getInstance("JKS");
trustStore.load(new FileInputStream("path/to/cacerts"), "changeit");
TrustManagerFactory trustManagerFactory = TrustManagerFactory
.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(trustStore);
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(),
new SecureRandom());
URL url = new URL("https://XXX.XXX.XXX.XXX/MyWebService");
connection = (HttpsURLConnection) url.openConnection();
connection.setSSLSocketFactory(sslContext.getSocketFactory());
connection.setRequestProperty("Content-Type", "text/xml");
connection.setRequestMethod("GET");
connection.setConnectTimeout(120000);
connection.connect();
我设法通过在openConnection调用之前直接放入以下内容来找到该错误的解决方法:
HttpsURLConnection.setDefaultHostnameVerifier((hostname, session) -> hostname.equals("XXX.XXX.XXX.XXX"));
只给我:
javax.net.ssl.SSLHandshakeException:sun.security.validator.ValidatorException:PKIX路径构建失败:sun.security.provider.certpath.SunCertPathBuilderException:无法找到所请求目标的有效证书路径
我找不到任何有关此问题的决议。我已经尝试导出证书并通过keytool将其添加到cacert,但它没有帮助,我没有想法。任何帮助表示赞赏。
答案 0 :(得分:0)
事实证明,我只需要下载服务器证书并将其添加到cacerts而不是使用pkcs12文件。