网上的找的代码会出现证书找的不对的问题,此代码经过测试解决了此问题。

 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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;

public class CerCheckUtil
{
    private static final Logger log = LoggerFactory.getLogger(CerCheckUtil.class);

    public static X509Certificate parseCerFromDomain(String appUrl) {
        HttpsURLConnection connection = null;
        try {
            URL url = new URL(appUrl);
            connection = (HttpsURLConnection) url.openConnection();
            TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager()
            {
                public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                    return new X509Certificate[0];
                }

                public void checkClientTrusted(X509Certificate[] certs, String authType) {
                }

                public void checkServerTrusted(X509Certificate[] certs, String authType) {
                }
            } };
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            connection.setSSLSocketFactory(sc.getSocketFactory());
            connection.connect();
            if (connection.getServerCertificates().length == 0) {
                return null;
            }
            return (X509Certificate) connection.getServerCertificates()[0];
        }
        catch (Exception e) {
            log.error("获取证书报错", e);
            return null;
        }
        finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
    }

    public static void main(String[] args) throws IOException, NoSuchAlgorithmException, KeyManagementException {
        String[] list = new String[] { "https://zhidao.epoint.com.cn" };
        for (String d : list) {
            try {
                System.out.println(d);
                X509Certificate certificate = CerCheckUtil.parseCerFromDomain(d);
                if (certificate!=null) {
                    System.out.println(certificate.getSubjectDN().getName());
                }
                System.out.println("------------------------------");
            }
            catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}