如何获取服务器证书链,然后验证它在 Java 中是否有效且受信任

2022-09-02 09:41:11

我需要创建与远程服务器的 Https 连接,然后检索并验证证书。

我已经建立了良好的连接:

try {  
    url = new URL(this.SERVER_URL);  
    HttpURLConnection con = (HttpURLConnection) url.openConnection();   
    HttpsURLConnection secured = (HttpsURLConnection) con;  
    secured.connect(); 
}  

但是似乎方法未由类型定义。getServerCertificateChain()HttpsURLConnection

那么如何检索服务器证书链呢?我的理解是,应该返回一个对象数组,并且此类具有我可用于查询证书的方法。getServerCertificateChain()X509Certificate

我需要验证:

  1. 证书有效且受信任,
  2. 根据证书序列号检查证书吊销列表分发点
  3. 确保它没有过期,并且
  4. 检查证书中的URL是否与另一个匹配(我已经检索过)。

我迷路了,真的非常感谢任何帮助!


答案 1

您需要的方法是 getServerCertificates,而不是 。这里有一些很好的示例代码。getServerCertificateChain


编辑

添加了一些我自己的示例代码。对你来说是一个很好的起点。别忘了看看Javadocs for HttpsURLConnectionX509Certificate

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

答案 2

快速谷歌搜索将我带到了使用BouncyCastle的这个例子。我认为它更好地回答了这个问题。http://www.nakov.com/blog/2009/12/01/x509-certificate-validation-in-java-build-and-verify-chain-and-verify-clr-with-bouncy-castle/


推荐