獲取服務端https證書 - Java版
阿新 • • 發佈:2017-12-20
https certificate 接上篇,用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 |
與之前是一樣的。
獲取服務端https證書 - Java版