接上篇,用java代码实现一下获取远程服务端证书,还是拿新浪首页测试,上代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
|
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 |
与之前是一样的。
本文转自 BoyTNT 51CTO博客,原文链接:http://blog.51cto.com/boytnt/2052616,如需转载请自行联系原作者