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

Mar*_*c H 16 java x509certificate

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

我建立了良好的连接:

try {  
    url = new URL(this.SERVER_URL);  
    HttpURLConnection con = (HttpURLConnection) url.openConnection();   
    HttpsURLConnection secured = (HttpsURLConnection) con;  
    secured.connect(); 
}  
Run Code Online (Sandbox Code Playgroud)

但似乎getServerCertificateChain()方法未定义类型HttpsURLConnection.

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

我需要验证:

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

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

Per*_*ion 24

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


编辑

添加了一些我自己的示例代码.对你来说是个好的起点.不要忘记查看HttpsURLConnectionX509Certificate的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");
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • **警告**:上面的代码**不**完全验证链,它只检查证书是否在其有效期内。 (2认同)