Example usage for javax.net.ssl SSLContext getSocketFactory

List of usage examples for javax.net.ssl SSLContext getSocketFactory

Introduction

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

Prototype

public final SSLSocketFactory getSocketFactory() 

Source Link

Document

Returns a SocketFactory object for this context.

Usage

From source file:org.accada.epcis.repository.query.QuerySubscription.java

/**
 * Retrieves an "all-trusting" HTTP URL connection object, by disabling the
 * validation of certificates and overriding the default trust manager with
 * one that trusts all certificates./*  w w  w  . j  a  v  a2s. c om*/
 * 
 * @param url
 *            The URL on which a connection will be opened.
 * @return A HttpURLConnection connection object.
 * @throws IOException
 *             If an I/O error occurred.
 */
private HttpURLConnection getAllTrustingConnection(URL url) throws IOException {
    // 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) {
        }
    } };

    // Install the all-trusting trust manager
    try {
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (Exception e) {
        LOG.error("Unable to install the all-trusting trust manager", e);
    }
    return getConnection(url);
}

From source file:orca.ektorp.client.ContextualSSLSocketFactory.java

/**
 * @deprecated Use {@link SSLSocketFactory#SSLSocketFactory(SSLContext)}
 * @param sslContext SSL Context// ww w  . j  a  v a 2  s . com
 * @param nameResolver Host Name Resolver
 */
@Deprecated
public ContextualSSLSocketFactory(final SSLContext sslContext, final HostNameResolver nameResolver) {
    super();
    this.socketfactory = sslContext.getSocketFactory();
    this.hostnameVerifier = BROWSER_COMPATIBLE_HOSTNAME_VERIFIER;
    this.nameResolver = nameResolver;
}

From source file:com.polyvi.xface.extension.filetransfer.XFileTransferExt.java

/**
 * SSL?TrustManager???SSL?/*from   w w  w  . ja v  a 2  s  . c o m*/
 * HttpsURLConnection????
 */
private void trustAllHosts() {
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[] {};
        }

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

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

    // all-trusting TrustManager
    try {
        // ?SSL
        mDefaultSSLSocketFactory = HttpsURLConnection.getDefaultSSLSocketFactory();
        // TrustManager
        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(null, trustAllCerts, new SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (Exception e) {
        XLog.e(CLASS_NAME, e.getMessage());
    }
}

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

void downloadFileStream(SeadFile file, OutputStream destination)
        throws EntityNotFoundException, EntityTypeException {
    String filePath = null;//  w w  w  .  j av 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 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:android.webkit.cts.TestWebServer.java

private URLConnection openConnection(URL url)
        throws IOException, NoSuchAlgorithmException, KeyManagementException {
    if (mSsl) {/*from ww w.  j  a  v  a 2  s .c o  m*/
        // Install hostname verifiers and trust managers that don't do
        // anything in order to get around the client not trusting
        // the test server due to a lack of certificates.

        HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
        connection.setHostnameVerifier(new TestHostnameVerifier());

        SSLContext context = SSLContext.getInstance("TLS");
        TestTrustManager trustManager = new TestTrustManager();
        context.init(null, new TestTrustManager[] { trustManager }, null);
        connection.setSSLSocketFactory(context.getSocketFactory());

        return connection;
    } else {
        return url.openConnection();
    }
}

From source file:org.couchpotato.CouchPotato.java

private CouchPotato(String scheme, String hostname, int port, String path, String api, String username,
        String password, boolean trustAll, String trustMe) {
    this.scheme = scheme;
    this.hostName = hostname;
    this.port = port;
    this.path = path;
    this.api = api;
    this.username = username;
    this.password = password;
    this.trustAll = trustAll;

    if (this.username == null)
        this.username = "";
    if (this.password == null)
        this.password = "";

    // Configure SSL behavior based on user preferences
    Authenticator.setDefault(new CouchAuthenticator(username, password, hostname));
    HostnameVerifier verifier;/*from   ww w .  ja v a  2s .  c  om*/
    try {
        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager(trustAll, trustMe) },
                new SecureRandom());
        if (trustAll) {
            verifier = new AllowAllHostnameVerifier();
        } else {
            verifier = new StrictHostnameVerifier();
        }
        HttpsURLConnection.setDefaultSSLSocketFactory(ctx.getSocketFactory());
        HttpsURLConnection.setDefaultHostnameVerifier(verifier);
    } catch (NoSuchAlgorithmException e) {

    } catch (KeyManagementException e) {

    } catch (KeyStoreException e) {

    }
}

From source file:com.mytalentfolio.h_daforum.CconnectToServer.java

/**
 * Creates a new instance of {@code HttpsURLConnection} from the given
 * {@code context} and {@code hostnameVerifier}.
 * /*from  www.  jav  a2 s.  co m*/
 * @param context
 *            the TrustManagerFactory to get the SSLContext
 * @return the new {@code HttpsURLConnection} instance.
 * @throws IOException
 *             if an error occurs while opening the connection.
 */
private HttpsURLConnection getURLConnection(SSLContext context, HostnameVerifier hostnameVerifier)
        throws IOException {

    URL url = new URL("https://10.0.2.2/mycode/digitalSig.php");

    HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
    urlConnection.setDoOutput(true);
    urlConnection.setDoInput(true);
    urlConnection.setConnectTimeout(3000);
    urlConnection.setSSLSocketFactory(context.getSocketFactory());
    urlConnection.setHostnameVerifier(hostnameVerifier);

    return urlConnection;
}

From source file:com.openshift.internal.restclient.http.UrlConnectionHttpClient.java

/**
 * Sets a ssl socket factory that sets a filtered list of ciphers based on
 * the #excludedSSLCipherRegex to the given connection.
 * /*from  w  w  w.  ja  va 2 s .  co  m*/
 * @param sslContext
 * 
 * @param sslContext
 *            the ssl context that shall be used
 * @param url
 *            the url we are connecting to
 * @param connection
 *            the connection that the cipher filter shall be applied to
 */
protected SSLContext setFilteredCiphers(String excludedSSLCipherRegex, SSLContext sslContext,
        HttpsURLConnection connection) {
    if (excludedSSLCipherRegex != null) {
        connection.setSSLSocketFactory(new EnabledCiphersSSLSocketFactory(
                SSLUtils.filterCiphers(excludedSSLCipherRegex, getSupportedCiphers(sslContext)),
                sslContext.getSocketFactory()));
    }
    return sslContext;
}

From source file:org.ejbca.core.ejb.ocsp.OcspKeyRenewalSessionBean.java

private SSLSocketFactory getSSLSocketFactory() {
    final List<Integer> authenticationKeyBindingIds = internalKeyBindingMgmtSession
            .getInternalKeyBindingIds(authenticationToken, AuthenticationKeyBinding.IMPLEMENTATION_ALIAS);
    AuthenticationKeyBinding authenticationKeyBinding = null;
    for (Integer internalKeyBindingId : authenticationKeyBindingIds) {
        try {//from www.ja  v a2 s.  c o m
            final InternalKeyBinding internalKeyBinding = internalKeyBindingMgmtSession
                    .getInternalKeyBindingReference(authenticationToken, internalKeyBindingId);
            if (internalKeyBinding.getStatus().equals(InternalKeyBindingStatus.ACTIVE)) {
                // Use first active one
                authenticationKeyBinding = (AuthenticationKeyBinding) internalKeyBinding;
                break;
            }
        } catch (AuthorizationDeniedException e) {
            throw new RuntimeException(e);
        }
    }
    if (authenticationKeyBinding == null) {
        return null;
    }
    final CryptoToken cryptoToken = cryptoTokenManagementSession
            .getCryptoToken(authenticationKeyBinding.getCryptoTokenId());
    final X509Certificate sslCertificate = (X509Certificate) certificateStoreSession
            .findCertificateByFingerprint(authenticationKeyBinding.getCertificateId());
    final List<X509Certificate> chain = new ArrayList<X509Certificate>();
    chain.add(sslCertificate);
    chain.addAll(getCaCertificateChain(sslCertificate));
    final List<X509Certificate> trustedCertificates = getListOfTrustedCertificates(
            authenticationKeyBinding.getTrustedCertificateReferences());
    final String alias = authenticationKeyBinding.getKeyPairAlias();
    try {
        final TrustManager trustManagers[];
        if (trustedCertificates == null || trustedCertificates.isEmpty()) {
            trustManagers = new X509TrustManager[] { new X509TrustManagerAcceptAll() };
        } else {
            throw new RuntimeException("Configurable trust not yet implemented.");
        }
        final KeyManager keyManagers[] = new X509KeyManager[] {
                new ClientX509KeyManager(alias, cryptoToken.getPrivateKey(alias), chain) };
        // Now construct a SSLContext using these (possibly wrapped) KeyManagers, and the TrustManagers.
        // We still use a null SecureRandom, indicating that the defaults should be used.
        final SSLContext context = SSLContext.getInstance("TLS");
        context.init(keyManagers, trustManagers, null);
        // Finally, we get a SocketFactory, and pass it on.
        return context.getSocketFactory();
    } catch (KeyManagementException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (CryptoTokenOfflineException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:co.cask.cdap.gateway.router.NettyRouterHttpsTest.java

@Override
protected SocketFactory getSocketFactory() throws Exception {
    SSLContext sc = SSLContext.getInstance("TLS");
    sc.init(null, new TrustManager[] { new X509TrustManager() {
        @Override// w ww . j av a 2 s.c  o m
        public void checkClientTrusted(X509Certificate[] x509Certificates, String s)
                throws CertificateException {

        }

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

        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0];
        }
    } }, new java.security.SecureRandom());
    return sc.getSocketFactory();
}