Example usage for javax.net.ssl X509TrustManager X509TrustManager

List of usage examples for javax.net.ssl X509TrustManager X509TrustManager

Introduction

In this page you can find the example usage for javax.net.ssl X509TrustManager X509TrustManager.

Prototype

X509TrustManager

Source Link

Usage

From source file:open.hyperion.nimblestorage.connection.NimbleStorageAPIFactory.java

public ClientConfig configureClient() throws NoSuchAlgorithmException, KeyManagementException {

    TrustManager[] certs = new TrustManager[] { new X509TrustManager() {
        @Override/*from   w  w w. j a  va2 s  .  c  o  m*/
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }
    } };
    SSLContext ctx = null;
    try {
        ctx = SSLContext.getInstance("TLS");
        ctx.init(null, certs, new SecureRandom());
    } catch (java.security.GeneralSecurityException ex) {
    }
    HttpsURLConnection.setDefaultSSLSocketFactory(ctx.getSocketFactory());

    ClientConfig config = new DefaultClientConfig();
    try {
        config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES,
                new HTTPSProperties(new HostnameVerifier() {
                    @Override
                    public boolean verify(String hostname, SSLSession session) {
                        return true;
                    }
                }, ctx));
    } catch (Exception e) {
    }
    config.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
    return config;
}

From source file:eu.siacs.conversations.ui.ServiceBrowserFragment.java

public static boolean exists(String URLName) {

    X509TrustManager trustManager = new X509TrustManager() {

        @Override/*from w  w w .j av  a2 s. c o m*/
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
            // NOTE : This is where we can calculate the certificate's fingerprint,
            // show it to the user and throw an exception in case he doesn't like it
        }

        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }
    };

    // Create a trust manager that does not validate certificate chains
    X509TrustManager[] trustAllCerts = new X509TrustManager[] { trustManager };

    // Install the all-trusting trust manager
    SSLSocketFactory noSSLv3Factory = null;
    try {
        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
            noSSLv3Factory = new TLSSocketFactory(trustAllCerts, new SecureRandom());
        } else {
            noSSLv3Factory = sc.getSocketFactory();
        }
        HttpsURLConnection.setDefaultSSLSocketFactory(noSSLv3Factory);
    } catch (GeneralSecurityException e) {
    }

    try {
        HttpsURLConnection.setFollowRedirects(false);
        // note : you may also need
        //        HttpURLConnection.setInstanceFollowRedirects(false)
        URL url = new URL(URLName);
        HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
        con.setSSLSocketFactory(noSSLv3Factory);
        con.setRequestProperty("Accept-Encoding", "");
        //HttpsURLConnection.setDefaultHostnameVerifier(new NullHostNameVerifier());
        con.setHostnameVerifier(new NullHostNameVerifier(url.getHost()));
        con.setRequestMethod("HEAD");
        return (con.getResponseCode() == HttpsURLConnection.HTTP_OK);
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}

From source file:com.scsy150.util.OtherUtils.java

public static void trustAllHttpsURLConnection() {
    // Create a trust manager that does not validate certificate chains
    if (sslSocketFactory == null) {
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            @Override//from w w w  .  ja v  a  2s. c  o  m
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }

            @Override
            public void checkClientTrusted(X509Certificate[] certs, String authType) {
            }

            @Override
            public void checkServerTrusted(X509Certificate[] certs, String authType) {
            }
        } };
        try {
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, trustAllCerts, null);
            sslSocketFactory = sslContext.getSocketFactory();
        } catch (Throwable e) {
            LogUtil.e("", e.getMessage());
        }
    }

    if (sslSocketFactory != null) {
        HttpsURLConnection.setDefaultSSLSocketFactory(sslSocketFactory);
        HttpsURLConnection.setDefaultHostnameVerifier(
                org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    }
}

From source file:net.jradius.server.TCPListener.java

public void setConfiguration(ListenerConfigurationItem cfg, boolean noKeepAlive)
        throws KeyStoreException, NoSuchAlgorithmException, CertificateException, UnrecoverableKeyException,
        KeyManagementException, IOException {
    keepAlive = !noKeepAlive;//from   ww w.j a  v  a 2 s.  c  o  m
    config = cfg;

    Map props = config.getProperties();

    String s = (String) props.get("port");
    if (s != null)
        port = new Integer(s).intValue();

    s = (String) props.get("backlog");
    if (s != null)
        backlog = new Integer(s).intValue();

    if (keepAlive) {
        s = (String) props.get("keepAlive");
        if (s != null)
            keepAlive = new Boolean(s).booleanValue();
    }

    String useSSL = (String) props.get("useSSL");
    String trustAll = (String) props.get("trustAll");

    if (requiresSSL || "true".equalsIgnoreCase(useSSL)) {
        KeyManager[] keyManagers = null;
        TrustManager[] trustManagers = null;

        String keyManager = (String) props.get("keyManager");

        if (keyManager != null && keyManager.length() > 0) {
            try {
                KeyManager manager = (KeyManager) Configuration.getBean(keyManager);
                keyManagers = new KeyManager[] { manager };
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            String keystore = (String) props.get("keyStore");
            String keystoreType = (String) props.get("keyStoreType");
            String keystorePassword = (String) props.get("keyStorePassword");
            String keyPassword = (String) props.get("keyPassword");

            if (keystore != null) {
                if (keystoreType == null)
                    keystoreType = "pkcs12";

                KeyStore ks = KeyStore.getInstance(keystoreType);
                ks.load(new FileInputStream(keystore),
                        keystorePassword == null ? null : keystorePassword.toCharArray());

                KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
                kmf.init(ks, keyPassword == null ? null : keyPassword.toCharArray());
                keyManagers = kmf.getKeyManagers();
            }
        }

        String trustManager = (String) props.get("trustManager");

        if (trustManager != null && trustManager.length() > 0) {
            try {
                TrustManager manager = (TrustManager) Configuration.getBean(trustManager);
                trustManagers = new TrustManager[] { manager };
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if ("true".equalsIgnoreCase(trustAll)) {
            trustManagers = new TrustManager[] { new X509TrustManager() {
                public void checkClientTrusted(X509Certificate[] chain, String authType) {

                }

                public void checkServerTrusted(X509Certificate[] chain, String authType) {

                }

                public X509Certificate[] getAcceptedIssuers() {
                    return new X509Certificate[0];
                }
            } };
        } else {
            String keystore = (String) props.get("caStore");
            String keystoreType = (String) props.get("caStoreType");
            String keystorePassword = (String) props.get("caStorePassword");

            if (keystore != null) {
                if (keystoreType == null)
                    keystoreType = "pkcs12";

                KeyStore caKeys = KeyStore.getInstance(keystoreType);
                caKeys.load(new FileInputStream(keystore),
                        keystorePassword == null ? null : keystorePassword.toCharArray());
                TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
                tmf.init(caKeys);
                trustManagers = tmf.getTrustManagers();
            }
        }

        SSLContext sslContext = SSLContext.getInstance("SSLv3");
        sslContext.init(keyManagers, trustManagers, null);

        ServerSocketFactory socketFactory = sslContext.getServerSocketFactory();
        SSLServerSocket sslServerSocket = (SSLServerSocket) socketFactory.createServerSocket(port, backlog);
        serverSocket = sslServerSocket;

        if (sslWantClientAuth)
            sslServerSocket.setWantClientAuth(true);

        if (sslNeedClientAuth)
            sslServerSocket.setNeedClientAuth(true);

        if (sslEnabledProtocols != null)
            sslServerSocket.setEnabledProtocols(sslEnabledProtocols);

        if (sslEnabledCiphers != null)
            sslServerSocket.setEnabledCipherSuites(sslEnabledCiphers);

        usingSSL = true;
    } else {
        serverSocket = new ServerSocket(port, backlog);
    }

    serverSocket.setReuseAddress(true);
    setActive(true);
}

From source file:com.alibaba.openapi.client.rpc.AlibabaClientReactor.java

private void createIOEventDispatch(ClientPolicy policy, HttpParams params)
        throws NoSuchAlgorithmException, KeyManagementException {
    HttpProcessor httpproc = createHttpProcessor();
    ByteBufferAllocator allocator = new HeapByteBufferAllocator();
    ////HTTP I/O?I/O???I/O?HTTP???NHttpClientHandlerNHttpServiceHandler?HTTP??HTTP???(handler).
    AsyncNHttpClientHandler handler = new AsyncNHttpClientHandler(httpproc,
            new AliNHttpRequstExecutionHandler(new ProtocolProvider(policy), allocator),
            new DefaultConnectionReuseStrategy(), allocator, params);
    //        BufferingHttpClientHandler handler = new BufferingHttpClientHandler(httpproc, new MyHttpRequestExecutionHandler(),
    //                new DefaultConnectionReuseStrategy(), params);
    handler.setEventListener(new EventLogger());
    SSLContext sslcontext = SSLContext.getInstance("TLS");
    sslcontext.init(null, new TrustManager[] { new X509TrustManager() {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }//  w  w w. ja va2  s  .c  o  m

        public void checkServerTrusted(java.security.cert.X509Certificate[] arg0, String arg1)
                throws CertificateException {
        }

        public void checkClientTrusted(java.security.cert.X509Certificate[] arg0, String arg1)
                throws CertificateException {
        }
    } }, new SecureRandom());
    sslcontext.getClientSessionContext().setSessionCacheSize(200);
    sslcontext.getClientSessionContext().setSessionTimeout(30000);
    //dispatchIOhandler
    ioEventDispatch = new AutoSSLClientIOEventDispatch(handler, sslcontext, params);
}

From source file:bear.plugins.java.JenkinsCache.java

public static File download(String jdkVersion, File jenkinsCache, File tempDestDir, String jenkinsUri,
        String user, String pass) {
    try {/*  w ww.  ja v  a2  s .  c o m*/
        Optional<JDKFile> optional = load(jenkinsCache, jenkinsUri, jdkVersion);

        if (!optional.isPresent()) {
            throw new RuntimeException("could not find: " + jdkVersion);
        }

        String uri = optional.get().filepath;

        SSLContext sslContext = SSLContext.getInstance("TLSv1");

        sslContext.init(null, new TrustManager[] { new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                System.out.println("getAcceptedIssuers =============");
                return null;
            }

            public void checkClientTrusted(X509Certificate[] certs, String authType) {
                System.out.println("checkClientTrusted =============");
            }

            public void checkServerTrusted(X509Certificate[] certs, String authType) {
                System.out.println("checkServerTrusted =============");
            }
        } }, new SecureRandom());

        SSLSocketFactory sf = new SSLSocketFactory(sslContext);

        Scheme httpsScheme = new Scheme("https", 443, sf);
        SchemeRegistry schemeRegistry = new SchemeRegistry();

        Scheme httpScheme = new Scheme("http", 80, PlainSocketFactory.getSocketFactory());

        schemeRegistry.register(httpsScheme);
        schemeRegistry.register(httpScheme);

        DefaultHttpClient httpClient = new DefaultHttpClient(
                new PoolingClientConnectionManager(schemeRegistry));

        CookieStore cookieStore = new BasicCookieStore();
        BasicClientCookie cookie = new BasicClientCookie("gpw_e24", ".");
        cookie.setDomain("oracle.com");
        cookie.setPath("/");
        cookie.setSecure(true);

        cookieStore.addCookie(cookie);

        httpClient.setCookieStore(cookieStore);

        HttpPost httppost = new HttpPost("https://login.oracle.com");

        httppost.setHeader("Authorization",
                "Basic " + new String(Base64.encodeBase64((user + ":" + pass).getBytes()), "UTF-8"));

        HttpResponse response = httpClient.execute(httppost);

        int code = response.getStatusLine().getStatusCode();

        if (code != 302) {
            System.out.println(IOUtils.toString(response.getEntity().getContent()));
            throw new RuntimeException("unable to auth: " + code);
        }

        // closes the single connection
        //                EntityUtils.consumeQuietly(response.getEntity());

        httppost = new HttpPost(uri);

        httppost.setHeader("Authorization",
                "Basic " + new String(Base64.encodeBase64((user + ":" + pass).getBytes()), "UTF-8"));

        response = httpClient.execute(httppost);

        code = response.getStatusLine().getStatusCode();

        if (code != 302) {
            System.out.println(IOUtils.toString(response.getEntity().getContent()));
            throw new RuntimeException("to download: " + uri);
        }

        File file = new File(tempDestDir, optional.get().name);
        HttpEntity entity = response.getEntity();

        final long length = entity.getContentLength();

        final CountingOutputStream os = new CountingOutputStream(new FileOutputStream(file));

        System.out.printf("Downloading %s to %s...%n", uri, file);

        Thread progressThread = new Thread(new Runnable() {
            double lastProgress;

            @Override
            public void run() {
                while (!Thread.currentThread().isInterrupted()) {
                    long copied = os.getCount();

                    double progress = copied * 100D / length;

                    if (progress != lastProgress) {
                        System.out.printf("\rProgress: %s%%", LangUtils.toConciseString(progress, 1));
                    }

                    lastProgress = progress;

                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        break;
                    }
                }
            }
        }, "progressThread");

        progressThread.start();

        ByteStreams.copy(entity.getContent(), os);

        progressThread.interrupt();

        System.out.println("Download complete.");

        return file;
    } catch (Exception e) {
        throw Exceptions.runtime(e);
    }
}

From source file:org.apache.fineract.infrastructure.sms.scheduler.SmsMessageScheduledJobServiceImpl.java

/** 
 * prevents the SSL security certificate check 
 **///from   www. j a v a 2s .c  o  m
private void trustAllSSLCertificates() {
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        public void checkClientTrusted(X509Certificate[] certs, String authType) {
        }

        public void checkServerTrusted(X509Certificate[] certs, String authType) {
        }
    } };

    try {
        SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, trustAllCerts, new SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());

        // Create all-trusting host name verifier
        HostnameVerifier hostnameVerifier = new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        };

        // Install the all-trusting host verifier
        HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
    }

    catch (Exception e) {
        // do nothing
    }
}

From source file:be.fedict.trust.client.XKMS2Client.java

/**
 * If set, unilateral TLS authentication will occurs, verifying the server
 * {@link X509Certificate} specified {@link PublicKey}.
 * <p/>//from ww w.  jav a2s. co  m
 * WARNING: only works when using the JAX-WS RI.
 * 
 * @param publicKey
 *            public key to validate server TLS certificate against.
 */
public void setServicePublicKey(final PublicKey publicKey) {
    // Create TrustManager
    TrustManager[] trustManager = { new X509TrustManager() {

        public X509Certificate[] getAcceptedIssuers() {

            return null;
        }

        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {

            X509Certificate serverCertificate = chain[0];
            LOG.debug("server X509 subject: " + serverCertificate.getSubjectX500Principal().toString());
            LOG.debug("authentication type: " + authType);
            if (null == publicKey) {
                LOG.warn("not performing any server certificate validation at all");
                return;
            }

            try {
                serverCertificate.verify(publicKey);
                LOG.debug("valid server certificate");
            } catch (InvalidKeyException e) {
                throw new CertificateException("Invalid Key");
            } catch (NoSuchAlgorithmException e) {
                throw new CertificateException("No such algorithm");
            } catch (NoSuchProviderException e) {
                throw new CertificateException("No such provider");
            } catch (SignatureException e) {
                throw new CertificateException("Wrong signature");
            }
        }

        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {

            throw new CertificateException("this trust manager cannot be used as server-side trust manager");
        }
    } };

    // Create SSL Context
    try {
        SSLContext sslContext = SSLContext.getInstance("TLS");
        SecureRandom secureRandom = new SecureRandom();
        sslContext.init(null, trustManager, secureRandom);
        LOG.debug("SSL context provider: " + sslContext.getProvider().getName());

        // Setup TrustManager for validation
        Map<String, Object> requestContext = ((BindingProvider) this.port).getRequestContext();
        requestContext.put("com.sun.xml.ws.transport.https.client.SSLSocketFactory",
                sslContext.getSocketFactory());

    } catch (KeyManagementException e) {
        String msg = "key management error: " + e.getMessage();
        LOG.error(msg, e);
        throw new RuntimeException(msg, e);
    } catch (NoSuchAlgorithmException e) {
        String msg = "TLS algo not present: " + e.getMessage();
        LOG.error(msg, e);
        throw new RuntimeException(msg, e);
    }
}

From source file:com.lidroid.util.OtherUtils.java

public static void trustAllHttpsURLConnection() {
    // Create a trust manager that does not validate certificate chains
    if (sslSocketFactory == null) {
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            @Override/*from w  ww . j a v  a  2 s. c o  m*/
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }

            @Override
            public void checkClientTrusted(X509Certificate[] certs, String authType) {
            }

            @Override
            public void checkServerTrusted(X509Certificate[] certs, String authType) {
            }
        } };
        try {
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, trustAllCerts, null);
            sslSocketFactory = sslContext.getSocketFactory();
        } catch (Throwable e) {
            Logger.e(e.getMessage(), e);
        }
    }

    if (sslSocketFactory != null) {
        HttpsURLConnection.setDefaultSSLSocketFactory(sslSocketFactory);
        HttpsURLConnection.setDefaultHostnameVerifier(
                org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    }
}

From source file:com.example.zch.imspeak.utils.OtherUtils.java

public static void trustAllHttpsURLConnection() {
    // Create a trust manager that does not validate certificate chains
    if (sslSocketFactory == null) {
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            @Override//from   w  w w .jav  a2  s.co m
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }

            @Override
            public void checkClientTrusted(X509Certificate[] certs, String authType) {
            }

            @Override
            public void checkServerTrusted(X509Certificate[] certs, String authType) {
            }
        } };
        try {
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, trustAllCerts, null);
            sslSocketFactory = sslContext.getSocketFactory();
        } catch (Throwable e) {
            LogUtils.e(e.getMessage(), e);
        }
    }

    if (sslSocketFactory != null) {
        HttpsURLConnection.setDefaultSSLSocketFactory(sslSocketFactory);
        HttpsURLConnection.setDefaultHostnameVerifier(
                org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    }
}