如何从SSLSocket中提取X509Certificate []的实例?

时间:2013-03-05 06:29:53

标签: java ssl ssl-certificate

假设我有以下代码,它创建了一个google.com的SSL套接字,我想查看Google的证书。如何获得javax.security.cert.X509Certificate[]的实例?

import java.io.*;
import java.math.*;
import java.net.*;
import java.security.*;

import javax.net.ssl.*;
import javax.net.*;


public class MWE{
    public static void main(String[] args) throws Exception{
        SSLContext sslContext = SSLContext.getDefault();
        SocketFactory clientSocketFactory = sslContext.getSocketFactory();

        String remoteHost = "google.com";
        int remotePort = 443;
        SSLSocket socket = null;
        try {
            //Lookup the "common name" field of the certificate from the remote server:
            socket = (SSLSocket) clientSocketFactory.createSocket(remoteHost, remotePort);
            socket.setEnabledCipherSuites(socket.getSupportedCipherSuites());
            socket.startHandshake();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }

    }
}

我查看了所涉及的每个类的文档,但我还没有找到任何包含证书的数据结构的引用。

1 个答案:

答案 0 :(得分:3)

X509Certificate[] c = socket.getSession().getPeerCertificateChain();