2

与 HttpsURLConnection 建立 HTTPS 连接时,我需要将自己的证书验证步骤放入 SSL 握手中。我已经编写了自己的证书验证码来验证主机证书中的某些属性,例如Certificate Revocation Status using Online Certificate Status Protocol。在 Java 中包含此步骤的正确方法是什么。我可以将它添加为默认 HostNameVerifier 的一部分,如下所示,但有没有合适的方法来做到这一点?

HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
        HostnameVerifier verifier = HttpsURLConnection.getDefaultHostnameVerifier();
        public boolean verify(String s, SSLSession sslSession) {
            return verifier.verify(s, sslSession) && MyVerifier.doMyVerification(sslSession);
        }
    }); 
4

2 回答 2

2

想出了一个更干净的方法。可以使用我们自己的 TrustManager 来做自定义证书验证。这是代码,

public class Test {


public static void main(String [] args) throws Exception {
    SSLContext ctx = SSLContext.getInstance("TLS");
    ctx.init(new KeyManager[0], new TrustManager[] {new DefaultTrustManager()}, new SecureRandom());
    SSLContext.setDefault(ctx);

    URL url = new URL("https://www.google.com");
    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
    conn.setHostnameVerifier(new HostnameVerifier() {
        public boolean verify(String arg0, SSLSession arg1) {
            return true;
        }
    });
    System.out.println(conn.getResponseCode());
    conn.disconnect();
}

private static class DefaultTrustManager implements X509TrustManager {

    public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
    }

    public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
        //Do certificate verification here and throw exception if invalid
        throw new CertificateException();
    }

    public X509Certificate[] getAcceptedIssuers() {
        return null;
    }
}

}
于 2014-02-07T05:26:49.320 回答
-1

正确的方法是从SSLSession你那里获取对等证书HostnameVerifier并在那里检查。

于 2014-02-07T06:04:16.913 回答