java 获取服务器证书,如何获取服务器证书链,然后验证它在Java中是否有效和可信...

I need to create an Https connection with a remote server then retrieve and verify the certificate.

I have established the connection fine:

try {

url = new URL(this.SERVER_URL);

HttpURLConnection con = (HttpURLConnection) url.openConnection();

HttpsURLConnection secured = (HttpsURLConnection) con;

secured.connect();

}

But it seems getServerCertificateChain() method is undefined by the type HttpsURLConnection.

So how do I retrieve the server certificate chain? My understanding is that getServerCertificateChain() should return an array of X509Certificate objects and that this class has methods I can use to interrogate the certificate.

I need to verify that:

the certificate is valid and trusted,

check the Certificate Revocation List Distribution Point against the certificate serial number

make sure it isn't expired and

check that the URL in the certificate is matches another (which I already have retrieved ).

I'm lost and would really appreciate any help!

解决方案

The method you want is getServerCertificates, not getServerCertificateChain. There is some nice sample code here.

EDIT

Added some sample code of my own. Good starting point for you. Don't forget to look at the Javadocs for HttpsURLConnection and X509Certificate.

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");

}

}

}

}

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值