简体   繁体   English

带有pfx证书的Java Open HttpsUrlConnection

[英]Java Open HttpsUrlConnection with pfx Certificate

I am trying to connect to a secure web server programmatically. 我正在尝试以编程方式连接到安全的Web服务器。 I have the pfx certificate used to access the server and can access it via the browser. 我拥有用于​​访问服务器的pfx证书,并且可以通过浏览器访问它。 However I get the following error: 但是我收到以下错误:

java.security.cert.CertificateException: No subject alternative names present java.security.cert.CertificateException:没有主题替代名称

This code I am using: 我正在使用的代码:

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

I managed to find a workaround for that error by putting the following directly before the openConnection call: 通过将以下内容直接放在openConnection调用之前,我设法找到了该错误的解决方法:

HttpsURLConnection.setDefaultHostnameVerifier((hostname, session) -> hostname.equals("XXX.XXX.XXX.XXX"));

Only to give me: 只给我:

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 javax.net.ssl.SSLHandshakeException:sun.security.validator.ValidatorException:PKIX路径构建失败:sun.security.provider.certpath.SunCertPathBuilderException:找不到指向所请求目标的有效证书路径

I couldn't find any resolutions for this issue. 我找不到此问题的任何解决方案。 I've tried exporting the cert and adding it to cacert via keytool, but it doesn't help and I'm out of ideas. 我尝试导出证书,然后通过keytool将其添加到cacert,但是它没有帮助,我没有主意。 Any help is appreciated. 任何帮助表示赞赏。

因此,事实证明,我只需要下载服务器证书并将其添加到cacert中,而不是使用pkcs12文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM