Java Certificate Authority不在JRE时的SSL连接解决方​​案

Java SSL connection solution when Certificate Authority not in JRE

我正在尝试通过 https (SSL) 连接到 REST 服务,但无法正常工作。错误是 PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target。我查到问题是做Certificate Authority,一个叫www.identrust.com, has not been added to the default list of trusted authorities in the JRE's default keystore. See Will the cross root cover trust by the default list in the JDK/JRE? or Which browsers and operating systems support Let’s Encrypt.

的地方

我看到了一些建议的解决方案,例如忽略身份验证 (Java: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target), or importing the certificate into the JRE keystore (“unable to find valid certification path to requested target”, but browser says it's OK),但我想要做的是让我的 Java SE 应用程序通过 SSL 成功连接到具有来自www.identrust.com,以及任何其他有效站点。换句话说,我不想在每次 JDK 更新时更改 JRE 密钥库,我也不想忽略证书。

我可以从他们的网站 (Certificate Chain Download Instructions) 获得 identrust 的证书,那么如何将它添加到我的应用程序的 "chain of trust" 中?

忽略服务器证书检查是非常糟糕且不安全的做法。

将证书导入 JRE 密钥库也是不好的做法 - 考虑到 JRE 每年更新几次,这通常意味着您必须再次导入证书。

第三个也是最好的选择是显式信任丢失的 CA 证书(或直接信任服务器证书)。您可以通过将要信任的证书放在单独的 Java 密钥库中并将此密钥库包含在您的应用程序中(例如在 JAR 文件中)来做到这一点。

您可以使用系统 属性 javax.net.ssl.trustStore 或使用恕我直言的首选方式使用此处所述的自定义 SSLContext 实现来提供自定义信任库: