![](/img/trans.png)
[英]X509TrustManager - checkServerTrusted not called - is trusted server cert cached or is there a way to get certificate chain?
[英]How to get server certificate chain then verify it's valid and trusted in Java
我需要创建一个与远程服务器的 Https 连接,然后检索并验证证书。
我已经很好地建立了连接:
try {
url = new URL(this.SERVER_URL);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
HttpsURLConnection secured = (HttpsURLConnection) con;
secured.connect();
}
但似乎getServerCertificateChain()
方法未由HttpsURLConnection
类型定义。
那么如何检索服务器证书链呢? 我的理解是getServerCertificateChain()
应该返回一个X509Certificate
对象数组,并且这个类具有我可以用来查询证书的方法。
我需要验证:
我迷路了,非常感谢任何帮助!
您想要的方法是getServerCertificates ,而不是getServerCertificateChain
。 有一些很好的示例代码在这里。
编辑
添加了一些我自己的示例代码。 对你来说很好的起点。 不要忘记查看HttpsURLConnection和X509Certificate的Javadocs。
import java.net.URL;
import java.security.cert.Certificate;
import java.security.cert.CertificateExpiredException;
import java.security.cert.X509Certificate;
import javax.net.ssl.HttpsURLConnection;
public class TestSecuredConnection {
/**
* @param args
*/
public static void main(String[] args) {
TestSecuredConnection tester = new TestSecuredConnection();
try {
tester.testConnectionTo("https://www.google.com");
} catch (Exception e) {
e.printStackTrace();
}
}
public TestSecuredConnection() {
super();
}
public void testConnectionTo(String aURL) throws Exception {
URL destinationURL = new URL(aURL);
HttpsURLConnection conn = (HttpsURLConnection) destinationURL
.openConnection();
conn.connect();
Certificate[] certs = conn.getServerCertificates();
for (Certificate cert : certs) {
System.out.println("Certificate is: " + cert);
if(cert instanceof X509Certificate) {
try {
( (X509Certificate) cert).checkValidity();
System.out.println("Certificate is active for current date");
} catch(CertificateExpiredException cee) {
System.out.println("Certificate is expired");
}
}
}
}
}
使用 BouncyCastle 快速谷歌搜索让我看到了这个例子。 我认为它更好地回答了这个问题。 http://www.nakov.com/blog/2009/12/01/x509-certificate-validation-in-java-build-and-verify-chain-and-verify-clr-with-bouncy-castle/
Kirby和arulraj.net提到的这个示例代码已经在2011年从Apache CXF中移除,不支持OCSP。 Apache PDFBox项目“复活”了此代码,并添加了 OCSP 支持以及原始代码中缺少的更多功能,例如 CRL 签名检查。 从 2.0.13 版开始,改进的源代码可在示例子项目的 CertificateVerifier 类中找到。 它也可以在线获得,但有一些小的改进。
该代码并不声称是完美的,并且尚未检查根是否受信任。 在 JIRA 问题PDFBOX-3017 中跟踪开发。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.