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:com.googlesource.gerrit.plugins.hooks.rtc.network.RTCClient.java

private void setSSLTrustStrategy(boolean sslVerify) throws IOException {
    try {/*  w ww.j a  va2s  .  c  om*/
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[0];
            }

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

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

        if (sslVerify) {
            sc = SSLContext.getDefault();
        } else {
            sc = SSLContext.getInstance("SSL");
            sc.init(null, trustAllCerts, new SecureRandom());
        }

        SSLSocketFactory sf = new SSLSocketFactory(sc);
        sf.setHostnameVerifier(new AllowAllHostnameVerifier());
        SchemeRegistry schemeRegistry = httpclient.getConnectionManager().getSchemeRegistry();
        schemeRegistry.register(new Scheme("https", sf, 443));
    } catch (Exception any) {
        throw new IOException(any);
    }
}

From source file:edu.isi.misd.tagfiler.client.JakartaClient.java

/**
 * Initialize the HTTP client/*w  ww.j a v  a2s. c o  m*/
 * 
 * @param connections
 *            the maximum number of HTTP connections
 * @param socketBufferSize
 *            the socket buffer size
 * @param socketTimeout
 *            the socket buffer timeout
 */
private void init(int maxConnections, int socketBufferSize, int socketTimeout) throws Throwable {
    TrustManager easyTrustManager = new X509TrustManager() {

        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            // Oh, I am easy!
        }

        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            if (chain != null) {
                for (int i = 0; i < chain.length; i++) {
                    chain[i].checkValidity();
                }
            }
        }

        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

    };

    SSLContext sslcontext = SSLContext.getInstance("SSL");
    sslcontext.init(null, new TrustManager[] { easyTrustManager }, null);
    SSLSocketFactory sf = new SSLSocketFactory(sslcontext);
    sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

    BasicHttpParams params = new BasicHttpParams();
    params.setParameter("http.protocol.handle-redirects", false);
    params.setParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, socketBufferSize);
    params.setParameter(CoreConnectionPNames.SO_TIMEOUT, socketTimeout);

    // enable parallelism
    ConnPerRouteBean connPerRoute = new ConnPerRouteBean(maxConnections);
    ConnManagerParams.setMaxTotalConnections(params, maxConnections >= 2 ? maxConnections : 2);
    ConnManagerParams.setMaxConnectionsPerRoute(params, connPerRoute);

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    Scheme sch = new Scheme("https", sf, 443);
    schemeRegistry.register(sch);
    //schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    ClientConnectionManager cm = new ThreadSafeClientConnManager(params, schemeRegistry);

    httpclient = new DefaultHttpClient(cm, params);
    BasicCookieStore cookieStore = new BasicCookieStore();
    httpclient.setCookieStore(cookieStore);
}

From source file:com.github.reverseproxy.ReverseProxyJettyHandler.java

private SSLSocketFactory getSSLSocketFactory() throws NoSuchAlgorithmException, KeyManagementException {
    // Create a trust manager that does not validate certificate chains
    final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public void checkClientTrusted(final java.security.cert.X509Certificate[] chain,
                final String authType) {
        }/*from   www  .j  av a 2  s. co m*/

        public void checkServerTrusted(final java.security.cert.X509Certificate[] chain,
                final String authType) {
        }

        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    } };

    // Install the all-trusting trust manager
    final SSLContext sslContext = SSLContext.getInstance("SSL");
    sslContext.init(null, trustAllCerts, new java.security.SecureRandom());

    // Create an ssl socket factory with our all-trusting manager
    final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
    return sslSocketFactory;
}

From source file:org.jab.docsearch.spider.LinkFinder.java

/**
 * Method init/*from w ww  . j  a  va2 s.co m*/
 */
private void init() {
    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        @Override
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        @Override
        public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
            // nothing
        }

        @Override
        public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
            // nothing
        }
    } };

    // Install the all-trusting trust manager
    try {
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (Exception e) {
        logger.error("init() failed", e);
    }
}

From source file:org.wso2.carbon.andes.extensions.device.mgt.mqtt.authorization.client.OAuthRequestInterceptor.java

private static SSLSocketFactory getSimpleTrustedSSLSocketFactory() {
    try {//from  ww  w .ja v  a  2s .  c om
        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) {
            }
        } };
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        return sc.getSocketFactory();
    } catch (KeyManagementException | NoSuchAlgorithmException e) {
        return null;
    }
}

From source file:org.apache.ambari.server.scheduler.ExecutionScheduleManager.java

protected void buildApiClient() throws NoSuchAlgorithmException, KeyManagementException {

    Client client;/*from w w w . j  a v a 2 s.  c o  m*/

    String pattern;
    String url;

    if (configuration.getApiSSLAuthentication()) {
        pattern = "https://localhost:%s/";
        url = String.format(pattern, configuration.getClientSSLApiPort());

        // Create a trust manager that does not validate certificate chains
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] x509Certificates, String s)
                    throws CertificateException {

            }

            @Override
            public void checkServerTrusted(X509Certificate[] x509Certificates, String s)
                    throws CertificateException {

            }

            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }

        } };

        //Create SSL context
        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(null, trustAllCerts, new SecureRandom());

        //Install all trusting cert SSL context for jersey client
        ClientConfig config = new DefaultClientConfig();
        config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES,
                new HTTPSProperties(new HostnameVerifier() {
                    @Override
                    public boolean verify(String s, SSLSession sslSession) {
                        return true;
                    }
                }, sc));

        client = Client.create(config);

    } else {
        client = Client.create();
        pattern = "http://localhost:%s/";
        url = String.format(pattern, configuration.getClientApiPort());
    }

    this.ambariClient = client;
    this.ambariWebResource = client.resource(url);

    //Install auth filters
    ClientFilter csrfFilter = new CsrfProtectionFilter("RequestSchedule");
    ClientFilter tokenFilter = new InternalTokenClientFilter(tokenStorage);
    ambariClient.addFilter(csrfFilter);
    ambariClient.addFilter(tokenFilter);

}

From source file:ee.ria.xroad.common.request.ManagementRequestClient.java

private void createProxyHttpClient() throws Exception {
    log.trace("createProxyHttpClient()");

    TrustManager tm = new X509TrustManager() {
        @Override//from   w ww.  j  a v  a  2s.  c  o  m
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

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

        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    };

    KeyManager km = new X509ExtendedKeyManager() {

        private static final String ALIAS = "MgmtAuthKeyManager";

        @Override
        public String chooseClientAlias(String[] keyType, Principal[] issuers, Socket socket) {
            return ALIAS;
        }

        @Override
        public String chooseServerAlias(String keyType, Principal[] issuers, Socket socket) {
            return ALIAS;
        }

        @Override
        public X509Certificate[] getCertificateChain(String alias) {
            try {
                return new X509Certificate[] { InternalSSLKey.load().getCert() };
            } catch (Exception e) {
                log.error("Failed to load internal TLS key", e);

                return new X509Certificate[] {};
            }
        }

        @Override
        public String[] getClientAliases(String keyType, Principal[] issuers) {
            return null;
        }

        @Override
        public PrivateKey getPrivateKey(String alias) {
            try {
                return InternalSSLKey.load().getKey();
            } catch (Exception e) {
                log.error("Failed to load internal TLS key", e);

                return null;
            }
        }

        @Override
        public String[] getServerAliases(String keyType, Principal[] issuers) {
            return null;
        }

        @Override
        public String chooseEngineClientAlias(String[] keyType, Principal[] issuers, SSLEngine engine) {
            return ALIAS;
        }

        @Override
        public String chooseEngineServerAlias(String keyType, Principal[] issuers, SSLEngine engine) {
            return ALIAS;
        }
    };

    proxyHttpClient = createHttpClient(km, tm);
}

From source file:org.dataconservancy.dcs.access.http.SeadDatastreamServlet.java

private void getFile(SeadFile file, OutputStream destination) {

    String filePath = null;//from  w  w w.  jav a 2s.  c om
    if (file.getPrimaryLocation().getType() != null && file.getPrimaryLocation().getType().length() > 0
            && file.getPrimaryLocation().getLocation() != null
            && file.getPrimaryLocation().getLocation().length() > 0
            && file.getPrimaryLocation().getName() != null
            && file.getPrimaryLocation().getName().length() > 0) {
        if ((file.getPrimaryLocation().getName()
                .equalsIgnoreCase(ArchiveEnum.Archive.IU_SCHOLARWORKS.getArchive()))
                || (file.getPrimaryLocation().getName()
                        .equalsIgnoreCase(ArchiveEnum.Archive.UIUC_IDEALS.getArchive()))) {
            URLConnection connection = null;
            try {
                String location = file.getPrimaryLocation().getLocation();
                location = location.replace("http://maple.dlib.indiana.edu:8245/",
                        "https://scholarworks.iu.edu/");
                connection = new URL(location).openConnection();
                connection.setDoOutput(true);
                final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
                    @Override
                    public void checkClientTrusted(final X509Certificate[] chain, final String authType) {
                    }

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

                    @Override
                    public X509Certificate[] getAcceptedIssuers() {
                        return null;
                    }
                } };
                if (connection.getURL().getProtocol().equalsIgnoreCase("https")) {
                    final SSLContext sslContext = SSLContext.getInstance("SSL");
                    sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
                    final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
                    ((HttpsURLConnection) connection).setSSLSocketFactory(sslSocketFactory);
                }
                IOUtils.copy(connection.getInputStream(), destination);
            } catch (IOException e) {
                e.printStackTrace();
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
            } catch (KeyManagementException e) {
                e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
            }
            return;
        } else if (file.getPrimaryLocation().getType()
                .equalsIgnoreCase(ArchiveEnum.Archive.SDA.getType().getText())
                && file.getPrimaryLocation().getName().equalsIgnoreCase(ArchiveEnum.Archive.SDA.getArchive())) {
            filePath = file.getPrimaryLocation().getLocation();

            String[] pathArr = filePath.split("/");

            try {
                sftp = new Sftp(config.getSdahost(), config.getSdauser(), config.getSdapwd(),
                        config.getSdamount());
                sftp.downloadFile(filePath.substring(0, filePath.lastIndexOf('/')), pathArr[pathArr.length - 1],
                        destination);
                sftp.disConnectSession();
            } catch (JSchException e) {
                e.printStackTrace();
            } catch (SftpException e) {
                e.printStackTrace();
            }
        }
    } else {
        if (file.getSecondaryDataLocations() != null && file.getSecondaryDataLocations().size() > 0) {
            for (SeadDataLocation dataLocation : file.getSecondaryDataLocations()) {
                if (dataLocation.getType().equalsIgnoreCase(ArchiveEnum.Archive.SDA.getType().getText())
                        && dataLocation.getName().equalsIgnoreCase(ArchiveEnum.Archive.SDA.getArchive())) {
                    filePath = dataLocation.getLocation();

                    String[] pathArr = filePath.split("/");

                    try {
                        sftp = new Sftp(config.getSdahost(), config.getSdauser(), config.getSdapwd(),
                                config.getSdamount());
                        sftp.downloadFile(filePath.substring(0, filePath.lastIndexOf('/')),
                                pathArr[pathArr.length - 1], destination);
                        sftp.disConnectSession();
                    } catch (JSchException e) {
                        e.printStackTrace();
                    } catch (SftpException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
    return;
}

From source file:org.apache.stratos.adc.mgt.cli.CommandLineService.java

public boolean login(String serverURL, String username, String password, boolean validateLogin)
        throws CommandException {
    try {/*from  w  w  w .j  a v  a  2  s.c  om*/
        // Following code will avoid validating certificate
        SSLContext sc;
        // Get SSL context
        sc = SSLContext.getInstance("SSL");
        // Create empty HostnameVerifier
        HostnameVerifier hv = new HostnameVerifier() {
            public boolean verify(String urlHostName, SSLSession session) {
                return true;
            }
        };
        // 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) {
            }
        } };
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        SSLContext.setDefault(sc);
        HttpsURLConnection.setDefaultHostnameVerifier(hv);
    } catch (Exception e) {
        throw new RuntimeException("Error while authentication process!", e);
    }

    // Initialize Service Stub
    try {
        initializeApplicationManagementStub(serverURL, username, password);
    } catch (AxisFault e) {
        System.out.println("Error connecting to the back-end");
        throw new CommandException(e);
    }

    try {
        if (validateLogin) {
            String tenantDomain = stub.getTenantDomain();
            if (logger.isDebugEnabled()) {
                logger.debug("Tenant Domain {}", tenantDomain);
            }
            return (tenantDomain != null);
        } else {
            // Just return true as we don't need to validate
            return true;
        }
    } catch (RemoteException e) {
        System.out.println("Authentication failed!");
        throw new CommandException(e);
    }
}