java - 忽略过期的 ssl 证书 [英] java - ignore expired ssl certificate

查看:47
本文介绍了java - 忽略过期的 ssl 证书的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

SSL Certificate of website is expired. How to avoid it and make URL() work ?

推荐答案

您应该构建一个 TrustManager 来包装默认的信任管理器,捕获 CertificiateExpiredException 并忽略它.

You should build a TrustManager that wraps the default trust manager, catches the CertificiateExpiredException and ignores it.

注意:如此答案中所述,这是否安全在很大程度上取决于实现.特别是,它依赖于在其他所有内容都已正确检查之后最后进行的日期验证.

Note: as detailed in this answer, whether or not this is secure is very much implementation dependent. In particular, it relies on the date validation being done last, after everything else has been checked properly.

应该按照这些方法行事:

Something along these lines should work:

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());

信任管理器抛出 CertificateExceptions(有关详细信息,请参阅子类)当证书出现问题时.明确你想要捕捉/忽略的内容.您真正想要验证的所有内容都必须在您捕获的内容可能被抛出之前进行检查,否则您也必须手动验证它.任何比这更轻松的事情(特别是,不做任何事情,因此不会抛出任何异常)将完全忽略证书验证和验证,这与使用匿名密码套件或忽略身份验证大致相同.这将违背使用 SSL/TLS 的安全目的(而不是在到期日更加灵活).

The trust managers throw CertificateExceptions (see subclasses for details) when something is wrong with a certificate. Be specific in what you want to catch/ignore. Everything you really want validated has to be checked before what you catch is potentially thrown, or you'll have to validate it manually too. Anything more relaxed than this (in particular, not doing anything and therefore not throwing any exception) will ignore the certificate verification and validation altogether, which is about the same as using anonymous cipher suites or ignoring authentication. This would defeat the security purpose of using SSL/TLS (as opposed to being only a bit more flexible on the expiry date).

这篇关于java - 忽略过期的 ssl 证书的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆