[英]How can we do our own Certificate Verification Step in HTTPS
使用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);
}
});
想出了一種更清潔的方式。 可以使用我們自己的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;
}
}
}
正確的方法是從HostnameVerifier
的SSLSession
獲取對等證書,然后在此處進行檢查。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.