java – 忽略过期的SSL证书

URL myUrl = new URL("https://www....."); 

网站的SSL证书已过期。 如何避免它,使URL()的工作?

您应该构build包装默认信任pipe理器的TrustManager ,捕获CertificiateExpiredException并忽略它。

注意:正如在这个答案中详细说明的那样, 这是否安全取决于实现。 尤其是,在所有其他操作都被正确检查之后,它依赖于最后的datevalidation。

应该沿着这些线路工作:

 TrustManagerFactory tmf = TrustManagerFactory.getInstance( TrustManagerFactory.getDefaultAlgorithm()); // Initialise the TMF as you normally would, for example: tmf.init((KeyStore)null); TrustManager[] trustManagers = tmf.getTrustManagers(); final X509TrustManager origTrustmanager = (X509TrustManager)trustManagers[0]; TrustManager[] wrappedTrustManagers = new TrustManager[]{ new X509TrustManager() { public java.security.cert.X509Certificate[] getAcceptedIssuers() { return origTrustmanager.getAcceptedIssuers(); } public void checkClientTrusted(X509Certificate[] certs, String authType) { origTrustmanager.checkClientTrusted(certs, authType); } public void checkServerTrusted(X509Certificate[] certs, String authType) { try { origTrustmanager.checkServerTrusted(certs, authType); } catch (CertificateExpiredException e) {} } } }; SSLContext sc = SSLContext.getInstance("TLS"); sc.init(null, wrappedTrustManagers, null); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); 

CertificateException发生错误时,信任pipe理器抛出CertificateException (参见子类)。 具体在什么你想赶上/忽略。 所有你真正想validation的东西都必须在你捕获的东西被抛出之前检查,否则你也必须手动validation它。 比这更轻松的任何事情(特别是不做任何事情,因此不会抛出任何exception)将完全忽略证书validation和validation,这与使用匿名密码套件或忽略validation大致相同。 这将破坏使用SSL / TLS的安全性目的(而不是在有效期限内更灵活一点)。

您必须创build一个将忽略过期证书的自定义X509validation程序。 事实上,不会执行检查。

取自这里的代码: http : //exampledepot.com/egs/javax.net.ssl/TrustAll.html

 // Create a trust manager that does not validate certificate chains TrustManager[] trustAllCerts = new TrustManager[]{ new X509TrustManager() { public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted( java.security.cert.X509Certificate[] certs, String authType) { } public void checkServerTrusted( java.security.cert.X509Certificate[] certs, String authType) { } } }; // Install the all-trusting trust manager try { SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); } catch (Exception e) { } // Now you can access an https URL without having the certificate in the truststore // It should work with expired certificate as well try { URL myUrl = new URL("https://www....."); } catch (MalformedURLException e) { } 

我写了一个自定义的TrustManager来解决这个问题,你可以在https://gist.github.com/divergentdave/9a68d820e3610513bd​​4fcdc4ae5f91a1看到它。; 此TrustManager将有问题的X509Certificate包装在另一个类中,以禁用到期检查,同时保留所有其他validation。 (即匹配主机名,链接到可信的CA,签名有效等)