在与HttpsURLConnection建立HTTPS连接时,我需要在SSL握手中添加自己的证书验证步骤。我编写了自己的证书验证码,以使用在线证书状态协议验证主机证书中的某些属性是否说证书撤销状态。在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);
}
});
答案 0 :(得分: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;
}
}
}
答案 1 :(得分:-1)
正确的方法是从SSLSession
中的HostnameVerifier
获取同行证书并在那里查看。