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:io.restassured.config.SSLConfig.java

/**
 * Use relaxed HTTP validation. This means that you'll trust all hosts regardless if the SSL certificate is invalid. By using this
 * method you don't need to specify a keystore (see {@link #keyStore(String, String)} or trust store (see {@link #trustStore(java.security.KeyStore)}.
 *
 * @param protocol The standard name of the requested protocol. See the SSLContext section in the <a href="https://docs.oracle.com/javase/8/docs/technotes/guides/security/StandardNames.html#SSLContext">Java Cryptography Architecture Standard Algorithm Name Documentation</a> for information about standard protocol names.
 * @return A new SSLConfig instance/*from w  ww  . jav  a  2  s.  co m*/
 */
public SSLConfig relaxedHTTPSValidation(String protocol) {
    AssertParameter.notNull(protocol, "Protocol");
    SSLContext sslContext;
    try {
        sslContext = SSLContext.getInstance(protocol);
    } catch (NoSuchAlgorithmException e) {
        return SafeExceptionRethrower.safeRethrow(e);
    }

    // Set up a TrustManager that trusts everything
    try {
        sslContext.init(null, new TrustManager[] { new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }

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

            public void checkServerTrusted(X509Certificate[] certs, String authType) {
            }
        } }, new SecureRandom());
    } catch (KeyManagementException e) {
        return SafeExceptionRethrower.safeRethrow(e);
    }

    SSLSocketFactory sf = new SSLSocketFactory(sslContext, ALLOW_ALL_HOSTNAME_VERIFIER);
    return sslSocketFactory(sf);
}

From source file:org.codice.ddf.itests.common.cometd.CometDClient.java

private void doTrustAllCertificates() throws NoSuchAlgorithmException, KeyManagementException {
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        @Override/* w  w w . ja  v a2  s. c  om*/
        public void checkClientTrusted(X509Certificate[] x509Certificates, String s)
                throws CertificateException {
        }

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

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

    SSLContext sslContext = SSLContext.getInstance("SSL");
    sslContext.init(null, trustAllCerts, new SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
    HostnameVerifier hostnameVerifier = (s, sslSession) -> s.equalsIgnoreCase(sslSession.getPeerHost());
    HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
}

From source file:com.gorillalogic.monkeytalk.ant.RunTask.java

private String sendFormPost(String url, File proj, Map<String, String> additionalParams) throws IOException {

    HttpClient base = new DefaultHttpClient();
    SSLContext ctx = null;/*from   ww w  .  j ava 2  s  .c o m*/

    try {
        ctx = SSLContext.getInstance("TLS");
    } catch (NoSuchAlgorithmException ex) {
        log("exception in sendFormPost():");
    }

    X509TrustManager tm = new X509TrustManager() {
        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

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

        @Override
        public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType)
                throws java.security.cert.CertificateException {
        }
    };

    try {
        ctx.init(null, new TrustManager[] { tm }, null);
    } catch (KeyManagementException ex) {
        log("exception in sendFormPost():");
    }

    SSLSocketFactory ssf = new SSLSocketFactory(ctx);
    ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    ClientConnectionManager ccm = base.getConnectionManager();
    SchemeRegistry sr = ccm.getSchemeRegistry();
    sr.register(new Scheme("https", ssf, 443));

    HttpClient client = new DefaultHttpClient(ccm, base.getParams());
    try {
        HttpPost post = new HttpPost(url);

        MultipartEntity multipart = new MultipartEntity();
        for (String key : additionalParams.keySet())
            multipart.addPart(key, new StringBody(additionalParams.get(key), Charset.forName("UTF-8")));

        if (proj != null) {
            multipart.addPart("uploaded_file", new FileBody(proj));
        }

        post.setEntity(multipart);

        HttpResponse resp = client.execute(post);

        HttpEntity out = resp.getEntity();

        InputStream in = out.getContent();
        return FileUtils.readStream(in);
    } catch (Exception ex) {
        throw new IOException("POST failed", ex);
    } finally {
        try {
            client.getConnectionManager().shutdown();
        } catch (Exception ex) {
            // ignore
        }
    }
}

From source file:org.spiffyui.server.AuthServlet.java

/**
 * If the authentication URL uses SSL then we need to use an SSLContext to connect to 
 * it.  The JDK provides on by default that will work fine for us, but it is possible
 * for some code running in some other place of the JVM to set a new default and that
 * new default might not be compatible with the type of connection we want to create.
 * /*from w  w w . j  a v a2  s .co  m*/
 * The solution is to always set our own SSLContext.  In that case we will use a context
 * that allows any connection since we let administrators control this connection using
 * the whitelist so we know that we will only connect to trusted servers.
 * 
 * @param httpclient the HTTPClient making the connection
 * @param port       the port of the connection
 */
private void setupClientSSL(HttpClient httpclient, int port) {
    try {
        SSLSocketFactory sslSocketFactory = null;
        SSLContext sslContext = SSLContext.getInstance("TLS");
        TrustManager relaxedTrustManager = new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] chain, String authType)
                    throws CertificateException {
                /*
                 We accept all certs so there is nothing to test here.
                 */
            }

            @Override
            public void checkServerTrusted(X509Certificate[] chain, String authType)
                    throws CertificateException {
                /*
                 We accept all certs so there is nothing to test here.
                 */
            }

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                /*
                 This indicates that we accept all certificates
                 */
                return null;
            }
        };

        sslContext.init(null, new TrustManager[] { relaxedTrustManager }, new SecureRandom());
        sslSocketFactory = new SSLSocketFactory(sslContext);
        sslSocketFactory.setHostnameVerifier(new HostVerifier());

        /*
         No that we've configured our SSLContext we'll make sure our request uses it.
         */
        ClientConnectionManager connMgr = httpclient.getConnectionManager();
        SchemeRegistry schemeReg = connMgr.getSchemeRegistry();
        schemeReg.unregister("https");
        if (port != -1) {
            schemeReg.register(new Scheme("https", sslSocketFactory, port));
        } else {
            /*
             If the port is -1 it means they were access the server without a port.
             443 is the default port for SSL so we fill that in when making the connection.
             */
            schemeReg.register(new Scheme("https", sslSocketFactory, 443));
        }
    } catch (NoSuchAlgorithmException nsae) {
        LOGGER.throwing(AuthServlet.class.getName(), "setupClientSSL", nsae);
    } catch (KeyManagementException mke) {
        LOGGER.throwing(AuthServlet.class.getName(), "setupClientSSL", mke);
    }
}

From source file:org.dataconservancy.dcs.access.http.dataPackager.ZipPackageCreator.java

void downloadFileStream(SeadFile file, OutputStream destination)
        throws EntityNotFoundException, EntityTypeException {
    String filePath = null;/*from  www . ja va2s. com*/
    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 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 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:uk.ac.brighton.ci360.bigarrow.PlacesAPISearch.java

@SuppressWarnings("unused")
private HttpClient sslClient(HttpClient client) {
    try {//from  www .j a  v  a  2  s  .  c  o  m
        X509TrustManager tm = new X509TrustManager() {
            public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException {
            }

            public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException {
            }

            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };
        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(null, new TrustManager[] { tm }, null);
        SSLSocketFactory ssf = new MySSLSocketFactory(ctx);
        ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        ClientConnectionManager ccm = client.getConnectionManager();
        SchemeRegistry sr = ccm.getSchemeRegistry();
        sr.register(new Scheme("https", ssf, 443));
        return new DefaultHttpClient(ccm, client.getParams());
    } catch (Exception ex) {
        return null;
    }
}

From source file:io.hops.hopsworks.common.util.WebCommunication.java

private Client createClient() throws NoSuchAlgorithmException, KeyManagementException {
    if (DISABLE_CERTIFICATE_VALIDATION) {
        // Create a trust manager that does not validate certificate chains
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[0];
            }//from w w w. java2 s.com

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

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

        // Ignore differences between given hostname and certificate hostname
        HostnameVerifier hv = new HostnameVerifier() {
            public boolean verify(String hostAddress, SSLSession session) {
                return true;
            }
        };

        // Install the all-trusting trust manager
        SSLContext sc = SSLContext.getInstance("TLSv1.2");
        sc.init(null, trustAllCerts, new SecureRandom());
        ClientBuilder clientBuilder = ClientBuilder.newBuilder().hostnameVerifier(hv).sslContext(sc);
        return clientBuilder.build();
    } else {
        return ClientBuilder.newClient();
    }
}

From source file:com.gt.cl.http.CLSSLSocketFactory.java

public CLSSLSocketFactory(String s) throws NoSuchAlgorithmException, KeyManagementException {
    super();// w w  w . j  av a 2s.c o m
    // this.sslcontext = null;
    // this.socketfactory = HttpsURLConnection.getDefaultSSLSocketFactory();
    // this.nameResolver = null;
    this.sslcontext = SSLContext.getInstance(TLS);
    this.sslcontext.init(null, 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) {
        }
    } }, new SecureRandom());
    this.socketfactory = this.sslcontext.getSocketFactory();
    this.nameResolver = null;
}

From source file:itdelatrisu.opsu.Utils.java

/**
 * Switches validation of SSL certificates on or off by installing a default
 * all-trusting {@link TrustManager}.//ww w.  ja va2 s  .c o  m
 * @param enabled whether to validate SSL certificates
 * @author neu242 (http://stackoverflow.com/a/876785)
 */
public static void setSSLCertValidation(boolean enabled) {
    // create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0];
        }

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

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

    // install the all-trusting trust manager
    try {
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, enabled ? null : trustAllCerts, null);
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (Exception e) {
    }
}

From source file:org.bremersee.sms.GoyyaSmsService.java

/**
 * Creates an array of trust managers which trusts all X509 certificates.
 *//*from w w w .j ava2s  . co  m*/
protected TrustManager[] createTrustAllManagers() {
    return new TrustManager[] {

            new X509TrustManager() {

                /*
                 * (non-Javadoc)
                 * 
                 * @see javax.net.ssl.X509TrustManager#getAcceptedIssuers()
                 */
                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }

                /*
                 * (non-Javadoc)
                 * 
                 * @see
                 * javax.net.ssl.X509TrustManager#checkClientTrusted(java.
                 * security.cert.X509Certificate[], java.lang.String)
                 */
                @Override
                public void checkClientTrusted(X509Certificate[] certs, String authType) {
                }

                /*
                 * (non-Javadoc)
                 * 
                 * @see
                 * javax.net.ssl.X509TrustManager#checkServerTrusted(java.
                 * security.cert.X509Certificate[], java.lang.String)
                 */
                @Override
                public void checkServerTrusted(X509Certificate[] certs, String authType) {
                }
            } };
}