url.openConnection()之后,即使设置了trustStore属性,https / ssl也不起作用

时间:2018-10-15 15:08:58

标签: java ssl https

我遇到了一个关于https/ssl的怪异问题。
我有cacerts(即truststore)文件,其中包含从服务器正确下载的证书。我还在下面设置属性:

System.setProperty("javax.net.ssl.trustStore", getTrustStoreFile());
System.setProperty("javax.net.ssl.trustStorePassword", getSSLPassword());

当我使用https连接到服务器时(步骤A),这工作得很好。现在的问题是,在流程中,如果我在设置以上属性之前在行之前放置,步骤A开始给出异常。

new URL(url).openConnection();

例外是:

Exception in thread "main" 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
    at sun.security.ssl.Alerts.getSSLException(Alerts.java:192)

这似乎很奇怪。只需注意,异常仅发生在步骤A行中,而不在openConnection()代码上方。 似乎openConnection()在这里做得很时髦(似乎正在加载默认的java cacerts甚至在tha之后设置系统属性似乎都没有得到兑现)。
有人可以在这里给我点灯吗?

PS:我放置openConnection()代码以使用trustAll信任库下载服务器证书本身。所以我的流程是:
* url.openConnection(), connection.getServerCertificates()与自定义trustStore一起下载证书。
*将证书存储在信任库中。
*设置信任库系统属性。
*使用实际的https/SSL连接(步骤A)。
当我第二次运行时(第一次运行会将证书放入信任库中):
  after commenting step 1 above -> runs fine
  after just having url.openConnection() -> gives exception

0 个答案:

没有答案