accept All Certificate - Java Security

Java examples for Security:Certificate

Description

accept All Certificate

Demo Code


//package com.java2s;
import java.security.cert.CertificateException;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

public class Main {
    public static void acceptAllCerts() {
        // WARNING vulnerable to MITM attacks! currently only needed for
        // Bitfinex
        // follow https://github.com/timmolter/XChange/issues/52 for fix
        final TrustManager[] trustAllCerts = new TrustManager[1];

        trustAllCerts[0] = new X509TrustManager() {

            @Override//from w  ww.j a  va 2 s .  com
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }

            @Override
            public void checkClientTrusted(
                    final java.security.cert.X509Certificate[] arg0,
                    final String arg1) throws CertificateException {
            }

            @Override
            public void checkServerTrusted(
                    final java.security.cert.X509Certificate[] arg0,
                    final String arg1) throws CertificateException {
            }
        };
        try {
            final SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc
                    .getSocketFactory());
        } catch (final Exception e) {
        }
    }
}

Related Tutorials