2014-02-05 42 views
2

當使用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); 
     } 
    }); 

回答

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

'getAcceptedIssuers()'不允許返回null,並且這樣做不安全。同樣在'checkClientTrusted()'中什麼都不做。' – EJP

+0

是的,並且返回true驗證HostName也不安全,這很明顯。開發人員需要確定實施這些方法的安全方式。問題是「如何在HTTPS中執行自定義證書驗證步驟」,並且應該在checkServerTrusted(..)方法的自定義TrustManager中添加,而不是在HostNameVerifier中添加。 – Jeewantha

-1

正確的方法是讓從SSLSession同行證書在HostnameVerifier,並檢查它。

+0

HostNameVerifier是驗證主機的HostName並在不合適的情況下進行證書驗證。 -1爲非建設性的迴應。 – Jeewantha

+0

不適當的原因 – EJP

+1

@Jeeweentha不適當的*爲什麼?* NB我建議你查找'非建設性'的含義。這並不意味着你的想法。 – EJP

相關問題