Dikobraz Dikobraz - 1 year ago 120
Android Question

java - ignore expired ssl certificate

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

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

Answer Source

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(
// Initialise the TMF as you normally would, for example:

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

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).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download