2

HttpsURLConnection で HTTPS 接続を行うときに、SSL ハンドシェイクに独自の証明書検証ステップを入れる必要があります。ホスト証明書のいくつかのプロパティを確認するために、独自の証明書確認コードを作成しました。これは、 Online Certificate Status Protocolを使用してCertificate Revocation Statusと言います。このステップを 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 に答える