Next , use Java code to achieve a remote server certificate, or take Sina home test, on the code:
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 (); Will get the complete certificate chain.
X509Certificate cert = (x509certificate) certs[0]; CERT[0] is the lowest level of the certificate chain
SYSTEM.OUT.PRINTLN ("Serial number:" + cert.getserialnumber ());
SYSTEM.OUT.PRINTLN ("Issued to:" + Cert.getsubjectdn (). GetName ());
System.out.println ("Issuer:" + Cert.getissuerdn (). GetName ());
System.out.println ("Start:" + Cert.getnotbefore ());
System.out.println ("Expired:" + cert.getnotafter ());
SYSTEM.OUT.PRINTLN ("algorithm:" + cert.getsigalgname ());
System.out.println ("Fingerprint:" + 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 ();
}
}
Run to see the effect, get the output:
Sequence Number: 78653003708979598891221754220386804014 Issued to: cn=sina.com, ou= "Sina.com Technology (China) Co.,ltd", o= "Sina.com Technology (China) Co.,ltd", L=beijing, ST= BEIJING, C=CN Issued by: Cn=geotrust SSL Ca-g3, O=geotrust Inc., C=us Starting from: Tue Feb 08:00:00 CST 2017 Expires: Tue Nov 07:59:59 CST 2019 Algorithm: Sha256withrsa Fingerprint: 6ce7b869e4d6f77a31a967af2dc1b904fd059aa3 |
is the same as before.
Get the server-side HTTPS certificate-Java edition