获取服务端https证书 - Java版

接上篇,用java代码实现一下获取远程服务端证书,还是拿新浪首页测试,上代码:

package org.test;
 
import java.net.URL;
import java.security.MessageDigest;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import javax.net.ssl.HttpsURLConnection;
 
public class Application {
    public static void main(String[] args) throws Exception {
        URL url = new URL("https://www.sina.com.cn");
        HttpsURLConnection conn = (HttpsURLConnection)url.openConnection();
        conn.connect();
        Certificate[] certs = conn.getServerCertificates();    //会拿到完整的证书链
        X509Certificate cert = (X509Certificate)certs[0];    //cert[0]是证书链的最下层
        System.out.println("序号:" + cert.getSerialNumber());
        System.out.println("颁发给:" + cert.getSubjectDN().getName());
        System.out.println("颁发者:" + cert.getIssuerDN().getName());
        System.out.println("起始:" + cert.getNotBefore());
        System.out.println("过期:" + cert.getNotAfter());
        System.out.println("算法:" + cert.getSigAlgName());
        System.out.println("指纹:" + getThumbPrint(cert));
        conn.disconnect();
    }
 
    private static String getThumbPrint(X509Certificate cert) throws Exception {
        MessageDigest md = MessageDigest.getInstance("SHA-1");
        byte[] der = cert.getEncoded();
        md.update(der);
        byte[] digest = md.digest();
        return bytesToHexString(digest);
    }
     
    private static String bytesToHexString(byte[] src) {
        StringBuilder stringBuilder = new StringBuilder("");
        if (src == null || src.length <= 0) {
            return null;
        }
        for (int i = 0; i < src.length; i++) {
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }
}

 

 运行看效果,得到的输出:

序号:78653003708979598891221754220386804014
颁发给:CN=sina.com, OU="Sina.com Technology(China)Co.,ltd", O="Sina.com Technology(China)Co.,ltd", L=Beijing, ST=Beijing, C=CN
颁发者:CN=GeoTrust SSL CA - G3, O=GeoTrust Inc., C=US
起始:Tue Feb 21 08:00:00 CST 2017
过期:Tue Nov 26 07:59:59 CST 2019
算法:SHA256withRSA
指纹:6ce7b869e4d6f77a31a967af2dc1b904fd059aa3

 

与之前是一样的。

 

posted on 2018-07-11 11:09  BoyTNT  阅读(914)  评论(0编辑  收藏  举报

导航