我们如何在HTTPS中执行我们自己的证书验证步骤
问题描述:
当使用HttpsURLConnection进行HTTPS连接时,我需要将自己的证书验证步骤放在SSL握手中。我已经写了自己的证书验证码来验证主机证书中的某些属性,如证书吊销状态使用在线证书状态协议。在Java中包含此步骤的正确方法是什么?我可以将它作为默认HostNameVerifier的一部分添加,如下所示,但有没有适当的方法来做到这一点?我们如何在HTTPS中执行我们自己的证书验证步骤
HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
HostnameVerifier verifier = HttpsURLConnection.getDefaultHostnameVerifier();
public boolean verify(String s, SSLSession sslSession) {
return verifier.verify(s, sslSession) && MyVerifier.doMyVerification(sslSession);
}
});
答
想出一个更清洁的方式。可以使用我们自己的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;
}
}
}
'getAcceptedIssuers()'不允许返回null,并且这样做不安全。同样在'checkClientTrusted()'中什么都不做。' – EJP
是的,并且返回true验证HostName也不安全,这很明显。开发人员需要确定实施这些方法的安全方式。问题是“如何在HTTPS中执行自定义证书验证步骤”,并且应该在checkServerTrusted(..)方法的自定义TrustManager中添加,而不是在HostNameVerifier中添加。 – Jeewantha