我正在尝试使用以下 Java 代码建立测试 SSL 连接:
String httpsURL = "https://www.somehost.com";
URL myurl = new URL(httpsURL);
HttpsURLConnection con = (HttpsURLConnection)myurl.openConnection();
InputStream ins = con.getInputStream();
InputStreamReader isr=new InputStreamReader(ins);
BufferedReader in =new BufferedReader(isr);
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
当我连接到主机 A 时,一切正常 - 建立连接并收到响应。
但是,当我连接到受与主机 A 相同的机构颁发的证书保护的主机 B 时,我收到以下异常:
sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
到目前为止我读到的所有内容都表明我需要在我的 keystore 中安装证书,但是如果这是解决方案,那么为什么主机 A 工作而主机 B 不工作?
作为一个可能没有帮助的旁白 - 如果我编写一段类似的 C# 代码,那么主机 A 和 B 的连接都会成功协商 - 这同样适用于在浏览器中导航到 URL。
最佳答案
最可能的原因是,
- 主机 B 使用自签名证书。
- 证书由不在您的信任库中的 CA 签名。
- 该证书是使用中间证书签名的,但主机 B 配置错误,因此它不会发送带有中间证书的服务器证书。
对于#1、#2,您需要将证书或 CA 证书导入到您的信任库中。
对于 #3,告诉主机 B 发送中间证书。
关于java - 来自 Java 的 SSL 连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2760408/