用Java恢复SSL X509TrustManager

时间:2017-08-18 14:03:54

标签: java ssl ssl-certificate x509trustmanager

我有以下代码,有条件地(基于boolean)禁用SSL证书检查。

但是,如果我将boolean设置为false并重新运行我的代码,则SSL检查似乎仍然处于禁用状态(应该重新启用时)。

那么,与此相反的逻辑是什么,以便恢复检查?

if (bIgnoreSSL) {
  TrustManager[] trustAllCertificates = new TrustManager[] {
    new X509TrustManager()
    {
      @Override
      public X509Certificate[] getAcceptedIssuers() { return null; // Not relevant.}

      @Override
      public void checkClientTrusted(X509Certificate[] certs, String authType) { // Do nothing. Just allow them all. }

      @Override
      public void checkServerTrusted(X509Certificate[] certs, String authType){ // Do nothing. Just allow them all.}
    }
  };

   HostnameVerifier trustAllHostnames = new HostnameVerifier()
   {
        @Override
        public boolean verify(String hostname, SSLSession session) { return true; // Just allow them all. }
   };

        try
        {
            System.setProperty("jsse.enableSNIExtension", "false");
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, trustAllCertificates, new SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
            HttpsURLConnection.setDefaultHostnameVerifier(trustAllHostnames);
        }
        catch (GeneralSecurityException e)
        {
            throw new ExceptionInInitializerError(e);
        }
}
else {
  // Code to restore here (Opposite of above?)
}

1 个答案:

答案 0 :(得分:0)

另一种方法是首先将默认值保存在变量中,以便稍后恢复它们:

// save defaults (do this before setting another defaults)
HostnameVerifier defaultVerifier = HttpsURLConnection.getDefaultHostnameVerifier();
SSLSocketFactory defaultFactory = HttpsURLConnection.getDefaultSSLSocketFactory();

if (bIgnoreSSL) {
...
} else {
    // restore defaults
    HttpsURLConnection.setDefaultHostnameVerifier(defaultVerifier);
    HttpsURLConnection.setDefaultSSLSocketFactory(defaultFactory);
}

另一种选择(更好的一种,IMO)是设置所有连接的默认值,而是为每个连接设置:

HttpsURLConnection conn = // create connection

if (bIgnoreSSL) {
    // set custom verifier and factory only for this connection
    conn.setHostnameVerifier(trustAllHostnames);
    conn.setSSLSocketFactory(sc.getSocketFactory());
}
// no need to restore (else), as I didn't change the defaults

这仅更改指定连接的验证程序和工厂,而不会影响默认值(因此无需还原)。

相关问题