我要添加到我们的大型 Java 应用程序中的一个模块必须与另一家公司的 SSL 安全网站进行对话。问题是该站点使用自签名证书。我有一份证书副本以验证我没有遇到中间人攻击,我需要将此证书合并到我们的代码中,以便与服务器的连接成功。
这是基本代码:
void sendRequest(String dataPacket) {
String urlStr = "https://host.example.com/";
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setMethod("POST");
conn.setRequestProperty("Content-Length", data.length());
conn.setDoOutput(true);
OutputStreamWriter o = new OutputStreamWriter(conn.getOutputStream());
o.write(data);
o.flush();
}
如果没有对自签名证书进行任何额外的处理,这将在 conn.getOutputStream() 处死掉,但有以下例外:
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
....
Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
....
Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
理想情况下,我的代码需要教 Java 接受这个自签名证书,用于应用程序中的这一点,而不是其他任何地方。
我知道我可以将证书导入 JRE 的证书颁发机构存储区,这将允许 Java 接受它。如果我能提供帮助,那不是我想采取的方法。在我们所有客户的机器上为他们可能不使用的一个模块进行操作似乎非常具有侵入性;它会影响使用相同 JRE 的所有其他 Java 应用程序,即使任何其他 Java 应用程序访问该站点的可能性为零,我也不喜欢这样。这也不是一个简单的操作:在 UNIX 上,我必须获得访问权限才能以这种方式修改 JRE。
我还看到我可以创建一个 TrustManager 实例来进行一些自定义检查。看起来我什至可以创建一个 TrustManager,它在除此证书之外的所有实例中都委托给真正的 TrustManager。但是看起来 TrustManager 是全局安装的,我想这会影响我们应用程序的所有其他连接,这对我来说也不太合适。
设置 Java 应用程序以接受自签名证书的首选、标准或最佳方式是什么?我能完成上面提到的所有目标,还是不得不妥协?是否有涉及文件和目录以及配置设置以及几乎没有代码的选项?