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:com.zacwolf.commons.crypto._CRYPTOfactory.java

public static KeyStore addSiteTrustChain(final String sitehostname, final int httpsport,
        final KeyStore keystore, final char[] passphrase) throws KeyStoreException, NoSuchAlgorithmException,
        CertificateException, IOException, KeyManagementException {
    final SSLContext context = SSLContext.getInstance("TLS");
    final TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(keystore);//from   ww w  . j ava  2  s  .c  o m
    final X509TrustManager dtm = (X509TrustManager) tmf.getTrustManagers()[0];
    final MyTrustManager tm = new MyTrustManager(dtm);
    context.init(null, new TrustManager[] { tm }, null);
    final SSLSocketFactory factory = context.getSocketFactory();
    final SSLSocket socket = (SSLSocket) factory.createSocket(sitehostname, httpsport);
    socket.setSoTimeout(10000);
    try {
        System.out.println("Starting SSL handshake...");
        socket.startHandshake();
        socket.close();
        System.out.println("Certificate for server " + sitehostname + " is already trusted");
    } catch (SSLException e) {
        final X509Certificate[] chain = tm.chain;
        if (chain == null) {
            System.err.println("Could not obtain server certificate chain");
            return keystore;
        }
        System.out.println("Server sent " + chain.length + " certificate(s):");
        for (int i = 0; i < chain.length; i++) {
            final X509Certificate cert = chain[i];
            MessageDigest.getInstance("SHA1").update(cert.getEncoded());
            MessageDigest.getInstance("MD5").update(cert.getEncoded());
            final String alias = sitehostname + "-" + (i + 1);
            keystore.setCertificateEntry(alias, cert);
            System.out.println("Added certificate to keystore using alias '" + alias + "'");
        }
    }
    return keystore;
}

From source file:org.apache.synapse.config.SynapseConfigUtils.java

/**
 * Helper method to create a HttpSURLConnection with provided KeyStores
 *
 * @param url Https URL/*from   w  ww .j  a va  2 s  .c  o m*/
 * @param synapseProperties properties for extracting info
 * @param proxy if there is a proxy
 * @return gives out the connection created
 */
private static HttpsURLConnection getHttpsURLConnection(URL url, Properties synapseProperties, Proxy proxy) {

    if (log.isDebugEnabled()) {
        log.debug("Creating a HttpsURL Connection from given URL : " + url);
    }

    KeyManager[] keyManagers = null;
    TrustManager[] trustManagers = null;

    IdentityKeyStoreInformation identityInformation = KeyStoreInformationFactory
            .createIdentityKeyStoreInformation(synapseProperties);

    if (identityInformation != null) {
        KeyManagerFactory keyManagerFactory = identityInformation.getIdentityKeyManagerFactoryInstance();
        if (keyManagerFactory != null) {
            keyManagers = keyManagerFactory.getKeyManagers();
        }

    } else {
        if (log.isDebugEnabled()) {
            log.debug("There is no private key entry store configuration." + " Will use JDK's default one");
        }
    }

    TrustKeyStoreInformation trustInformation = KeyStoreInformationFactory
            .createTrustKeyStoreInformation(synapseProperties);

    if (trustInformation != null) {
        TrustManagerFactory trustManagerFactory = trustInformation.getTrustManagerFactoryInstance();
        if (trustManagerFactory != null) {
            trustManagers = trustManagerFactory.getTrustManagers();
        }
    } else {
        if (log.isDebugEnabled()) {
            log.debug("There is no trusted certificate store configuration." + " Will use JDK's default one");
        }
    }

    try {
        HttpsURLConnection connection;
        if (proxy != null) {
            connection = (HttpsURLConnection) url.openConnection(proxy);
        } else {
            connection = (HttpsURLConnection) url.openConnection();
        }
        //Create a SSLContext
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(keyManagers, trustManagers, null);
        connection.setSSLSocketFactory(sslContext.getSocketFactory());

        if (trustInformation != null) {
            // Determine is it need to overwrite default Host Name verifier
            boolean enableHostnameVerifier = true;
            String value = trustInformation.getParameter(KeyStoreInformation.ENABLE_HOST_NAME_VERIFIER);
            if (value != null) {
                enableHostnameVerifier = Boolean.parseBoolean(value);
            }

            if (!enableHostnameVerifier) {

                if (log.isDebugEnabled()) {
                    log.debug("Overriding default HostName Verifier." + "HostName verification disabled");
                }

                connection.setHostnameVerifier(new javax.net.ssl.HostnameVerifier() {
                    public boolean verify(String hostname, javax.net.ssl.SSLSession session) {
                        if (log.isTraceEnabled()) {
                            log.trace("HostName verification disabled");
                            log.trace("Host:   " + hostname);
                            log.trace("Peer Host:  " + session.getPeerHost());
                        }
                        return true;
                    }
                });
            } else {
                if (log.isDebugEnabled()) {
                    log.debug("Using default HostName verifier...");
                }
            }
        }
        return connection;

    } catch (NoSuchAlgorithmException e) {
        handleException("Error loading SSLContext ", e);
    } catch (KeyManagementException e) {
        handleException("Error initiation SSLContext with KeyManagers", e);
    } catch (IOException e) {
        handleException("Error opening a https connection from URL : " + url, e);
    }
    return null;
}

From source file:org.parosproxy.paros.network.SSLConnector.java

private static synchronized void readSupportedProtocols(SSLSocket sslSocket) {
    if (supportedProtocols == null) {
        logger.info("Reading supported SSL/TLS protocols...");
        String[] tempSupportedProtocols;
        if (sslSocket != null) {
            logger.info("Using an existing SSLSocket...");
            tempSupportedProtocols = sslSocket.getSupportedProtocols();
        } else {//from  w w  w  . j  a v a2 s .co m
            logger.info("Using a SSLEngine...");
            try {
                SSLContext ctx = SSLContext.getInstance(SSL);
                ctx.init(null, null, null);
                try {
                    tempSupportedProtocols = ctx.createSSLEngine().getSupportedProtocols();
                } catch (UnsupportedOperationException e) {
                    logger.warn("Failed to use SSLEngine. Trying with unconnected socket...", e);
                    try (SSLSocket socket = (SSLSocket) ctx.getSocketFactory().createSocket()) {
                        tempSupportedProtocols = socket.getSupportedProtocols();
                    }
                }
            } catch (NoSuchAlgorithmException | KeyManagementException | IOException e) {
                logger.error(
                        "Failed to read the SSL/TLS supported protocols." + " Using default protocol versions: "
                                + Arrays.toString(FAIL_SAFE_DEFAULT_ENABLED_PROTOCOLS),
                        e);
                tempSupportedProtocols = FAIL_SAFE_DEFAULT_ENABLED_PROTOCOLS;
            }
        }
        Arrays.sort(tempSupportedProtocols);
        supportedProtocols = tempSupportedProtocols;
        logger.info("Done reading supported SSL/TLS protocols: " + Arrays.toString(supportedProtocols));
    }
}

From source file:com.flipzu.flipzu.FlipInterface.java

/**
 * Trust every server - dont check for any certificate
 *///  www  .j ava 2 s  .c o  m
private static void trustAllHosts() {
    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return new java.security.cert.X509Certificate[] {};
        }

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

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

    // Install the all-trusting trust manager
    try {
        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (Exception e) {
        Log.e(TAG, "trustAllHosts ERROR", e.getCause());
    }
}

From source file:jetbrains.buildServer.vmgr.agent.Utils.java

private static SSLSocketFactory getSocketFactory() throws NoSuchAlgorithmException, KeyManagementException {
    SSLContext sslContext = SSLContext.getInstance("TLS");
    TrustManager tm = new X509TrustManager() {
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }/*from w  w w . j a v a 2 s  . com*/

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

        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    };
    sslContext.init(null, new TrustManager[] { tm }, null);
    return sslContext.getSocketFactory();
}

From source file:org.eclipse.lyo.testsuite.server.util.SSLProtocolSocketFactory.java

public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
    SSLContext ctx = getSSLContext();
    SSLSocketFactory sf = ctx.getSocketFactory();
    Socket socket = sf.createSocket(host, port);
    return socket;
}

From source file:org.eclipse.lyo.testsuite.server.util.SSLProtocolSocketFactory.java

public Socket createSocket(Socket socket, String host, int port, boolean autoclose)
        throws IOException, UnknownHostException {
    SSLContext ctx = getSSLContext();
    SSLSocketFactory sf = ctx.getSocketFactory();
    Socket newSocket = sf.createSocket(socket, host, port, autoclose);
    return newSocket;
}

From source file:com.groupon.odo.bmp.BrowserMobProxyHandler.java

/**
 * Returns a OkHttpClient that ignores SSL cert errors
 * @return/*from   w  ww . j a v a  2s  .  c o m*/
 */
private static OkHttpClient getUnsafeOkHttpClient() {
    try {
        // Create a trust manager that does not validate certificate chains
        final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            @Override
            public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType)
                    throws CertificateException {
            }

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

            @Override
            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();

        OkHttpClient okHttpClient = new OkHttpClient();
        okHttpClient.setSslSocketFactory(sslSocketFactory);
        okHttpClient.setHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });

        return okHttpClient;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:io.apiman.gateway.platforms.servlet.connectors.ssl.SSLSessionStrategyFactory.java

/**
 * <strong><em>Do not use in production</em></strong>
 * <p>/*from   w ww  . ja  v a2 s.  c o m*/
 * Returns an SSLSessionStrategy that trusts any Certificate.
 * <p>
 * Naturally, this is vulnerable to a raft of MIITM and forgery attacks, so users should exercise extreme
 * caution and only use it for development purposes.
 *
 * @return the ssl strategy
 */
public static SSLSessionStrategy buildUnsafe() {
    System.err.println("ATTENTION: SSLSessionStrategy will trust *any* certificate." //$NON-NLS-1$
            + " This is extremely unsafe for production. Caveat utilitor!"); //$NON-NLS-1$

    try {
        SSLContext sslContext = SSLContext.getInstance("TLS"); //$NON-NLS-1$

        // This accepts anything.
        sslContext.init(null, new X509TrustManager[] { new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] chain, String authType)
                    throws CertificateException {
            }

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

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[0];
            }
        } }, new SecureRandom());

        return new SSLSessionStrategy(ALLOW_ANY, sslContext.getSocketFactory());

    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:edu.vt.middleware.ldap.ssl.TLSSocketFactory.java

/**
 * Creates the underlying SSLContext using truststore and keystore attributes
 * and makes this factory ready for use. Must be called before factory can be
 * used./*  w w  w  . j  a  v  a2  s  .c  o m*/
 *
 * @throws  GeneralSecurityException  if the SSLContext cannot be created
 */
public void initialize() throws GeneralSecurityException {
    final SSLContext ctx = this.getSSLContextInitializer().initSSLContext(DEFAULT_PROTOCOL);
    this.factory = ctx.getSocketFactory();
}