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.apache.fineract.restwebservice.PlatformRestClient.java

/**
 * Skip SSL certificate verification//from  w ww. j av a 2  s.c o  m
 */
private void skipSslCertificateVerification() {
    final TrustManager[] trustManager = new TrustManager[] { new X509TrustManager() {
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

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

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

    try {
        // get the SSL context object
        SSLContext sslContext = SSLContext.getInstance("SSL");

        // initialize the SSL context
        sslContext.init(null, trustManager, new SecureRandom());

        // Set the default SSLSocketFactory
        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) {
    }
}

From source file:nl.armatiek.xslweb.configuration.Context.java

private void initProperties() throws Exception {
    File propsFile = new File(homeDir, "config" + File.separatorChar + Definitions.FILENAME_PROPERTIES);
    this.properties = XSLWebUtils.readProperties(propsFile);
    this.trustAllCerts = new Boolean(properties.getProperty(Definitions.PROPERTYNAME_TRUST_ALL_CERTS, "false"));
    if (trustAllCerts) {
        TrustManager[] trustAllCertsManager = new TrustManager[] { new X509TrustManager() {
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }//from   w w  w .jav a2  s.c o m

            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, trustAllCertsManager, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    }
    this.parserHardening = new Boolean(
            this.properties.getProperty(Definitions.PROPERTYNAME_PARSER_HARDENING, "false"));
}

From source file:org.apache.nifi.minifi.c2.integration.test.AbstractTestSecure.java

protected HttpsURLConnection openUrlConnection(String url, SSLContext sslContext) throws IOException {
    DockerPort dockerPort = docker.containers().container("squid").port(3128);
    HttpsURLConnection httpURLConnection = (HttpsURLConnection) new URL(url).openConnection(new Proxy(
            Proxy.Type.HTTP, new InetSocketAddress(dockerPort.getIp(), dockerPort.getExternalPort())));
    httpURLConnection.setSSLSocketFactory(sslContext.getSocketFactory());
    return httpURLConnection;
}

From source file:org.sonatype.nexus.internal.email.EmailManagerImpl.java

/**
 * Apply server configuration to email./* ww  w  .ja va 2 s.c  om*/
 */
@VisibleForTesting
Email apply(final EmailConfiguration configuration, final Email mail) throws EmailException {
    mail.setHostName(configuration.getHost());
    mail.setSmtpPort(configuration.getPort());
    mail.setAuthentication(configuration.getUsername(), configuration.getPassword());

    mail.setStartTLSEnabled(configuration.isStartTlsEnabled());
    mail.setStartTLSRequired(configuration.isStartTlsRequired());
    mail.setSSLOnConnect(configuration.isSslOnConnectEnabled());
    mail.setSSLCheckServerIdentity(configuration.isSslCheckServerIdentityEnabled());
    mail.setSslSmtpPort(Integer.toString(configuration.getPort()));

    // default from address
    if (mail.getFromAddress() == null) {
        mail.setFrom(configuration.getFromAddress());
    }

    // apply subject prefix if configured
    String subjectPrefix = configuration.getSubjectPrefix();
    if (subjectPrefix != null) {
        String subject = mail.getSubject();
        mail.setSubject(String.format("%s %s", subjectPrefix, subject));
    }

    // do this last (mail properties are set up from the email fields when you get the mail session)
    if (configuration.isNexusTrustStoreEnabled()) {
        SSLContext context = trustStore.getSSLContext();
        Session session = mail.getMailSession();
        Properties properties = session.getProperties();
        properties.remove(EmailConstants.MAIL_SMTP_SOCKET_FACTORY_CLASS);
        properties.put(EmailConstants.MAIL_SMTP_SSL_ENABLE, true);
        properties.put("mail.smtp.ssl.socketFactory", context.getSocketFactory());
    }

    return mail;
}

From source file:org.mule.providers.ldap.LdapSASLConnector.java

protected void doInitialise() throws InitialisationException {

    // if (isForceJDK14())
    // {/*  w w w . j a va  2s .co  m*/
    // logger.debug("forcing JDK 1.4 SASL mode");
    Security.addProvider(new com.novell.sasl.client.SaslProvider());
    // }
    /*
     * else { Provider sunSASL = Security.getProvider("SunSASL");
     * 
     * if (sunSASL != null) { logger .debug("SunSASL implementation (JDK >=
     * 1.5) detected. Use it."); try { Sasl.setSaslClientFactory(new
     * SaslBridgeClientFactory()); } catch (RuntimeException e) {
     * logger.warn(e.toString()); } } else { logger .debug("No SunSASL
     * implementation (JDK >= 1.5 detected. Fall back to JDK 1.4 mode");
     * Security.addProvider(new com.novell.sasl.client.SaslProvider()); } }
     */

    if (logger.isDebugEnabled()) {

        Provider[] ps = Security.getProviders();
        for (int i = 0; i < ps.length; i++) {
            Provider provider = ps[i];
            logger.debug(provider.getClass() + "/" + provider.getName() + "/" + provider.getVersion() + "/"
                    + provider.getInfo());

        }
    }

    if (MECHANISM_DIGEST_EXTERNAL.equals(mechanism)) {

        try {
            if (trustAll) {
                SSLContext context = SSLContext.getInstance("TLS");
                context.init(null, trustAll ? TrustAllCertsManager.getTrustAllCertsManager() : null, null);

                // certificate_unknown
                ssf = new LDAPJSSESecureSocketFactory(context.getSocketFactory());
            } else {
                if (StringUtils.isEmpty(trustStore)) {
                    throw new InitialisationException(new IllegalArgumentException(
                            "Either trustAll value must be true or the trustStore parameter must be set"),
                            this);
                }

                File trustStoreFile = new File(trustStore);

                if (!trustStoreFile.exists() || !trustStoreFile.canRead()) {
                    throw new InitialisationException(new IllegalArgumentException("truststore file "
                            + trustStoreFile.getAbsolutePath() + " do not exist or is not readable"), this);
                }

                System.setProperty("javax.net.ssl.trustStore", trustStore);

                logger.debug("truststore set to " + trustStoreFile.getAbsolutePath());

                ssf = new LDAPJSSESecureSocketFactory();
            }
            // pix path
            // ssf = new LDAPJSSESecureSocketFactory((SSLSocketFactory)
            // SSLSocketFactory.getDefault());

            // TODO SSL<->TLS (TLS maybe require startTLS() call on lc
            // ssf = new LDAPJSSEStartTLSFactory();
        } catch (KeyManagementException e) {
            throw new InitialisationException(e, this);
        } catch (NoSuchAlgorithmException e) {
            throw new InitialisationException(e, this);
        }

    }

    super.doInitialise();
}

From source file:it.jnrpe.client.JNRPEClient.java

/**
 * Inovoke a command installed in JNRPE.
 * // w  w w .j  a va  2 s  . c  o m
 * @param sCommandName
 *            The name of the command to be invoked
 * @param arguments
 *            The arguments to pass to the command (will substitute the
 *            $ARGSx$ parameters)
 * @return The value returned by the server
 * @throws JNRPEClientException
 *             Thrown on any communication error.
 */
public final ReturnValue sendCommand(final String sCommandName, final String... arguments)
        throws JNRPEClientException {
    SocketFactory socketFactory;

    Socket s = null;
    try {
        if (!useSSL) {
            socketFactory = SocketFactory.getDefault();
        } else {
            SSLContext sslContext = SSLContext.getInstance("TLSv1.2");

            sslContext.init(null, new TrustManager[] { getTrustManager() }, new SecureRandom());

            socketFactory = sslContext.getSocketFactory();
        }

        s = socketFactory.createSocket();
        if (weakCipherSuitesEnabled) {
            SSLSocket ssl = (SSLSocket) s;
            ssl.setEnabledCipherSuites(ssl.getSupportedCipherSuites());
        }

        s.setSoTimeout((int) TimeUnit.SECOND.convert(communicationTimeout));
        s.connect(new InetSocketAddress(serverIPorURL, serverPort));
        JNRPERequest req = new JNRPERequest(sCommandName, arguments);

        s.getOutputStream().write(req.toByteArray());

        InputStream in = s.getInputStream();
        JNRPEResponse res = new JNRPEResponse(in);

        return new ReturnValue(Status.fromIntValue(res.getResultCode()), res.getMessage());
    } catch (RuntimeException re) {
        throw re;
    } catch (Exception e) {
        throw new JNRPEClientException(e);
    } finally {
        if (s != null) {
            try {
                s.close();
            } catch (IOException e) {
                // Ignore
            }
        }
    }
}

From source file:org.openadaptor.util.hosting.HostedConnection.java

protected HostedConnection() {
    log.debug("Installing all-trusting Security manager");

    SSLContext sc;
    try {/*  ww w .ja  v a2 s.  com*/
        sc = SSLContext.getInstance("SSL");
        sc.init(null, trustManagers, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        new URL("https://not.real");
    } catch (NoSuchAlgorithmException e) {
        fail("Failed to establish SSL context", e);

    } catch (KeyManagementException e) {
        fail(e.getMessage(), e);

    } catch (MalformedURLException e) {
        fail("Failed to setup security manager " + e);
    }
}

From source file:org.ejbca.core.protocol.ocsp.OCSPUnidClient.java

private SSLSocketFactory getSSLFactory() throws IOException, NoSuchAlgorithmException,
        UnrecoverableKeyException, KeyStoreException, CertificateException, KeyManagementException {

    final KeyManager km[];
    final TrustManager tm[];

    // Put the key and certs in the user keystore (if available)
    if (this.ks != null) {
        final KeyManagerFactory kmf;
        kmf = KeyManagerFactory.getInstance("SunX509");
        kmf.init(this.ks, this.passphrase.toCharArray());
        km = kmf.getKeyManagers();// w  w w  .  ja v  a 2  s .  co  m
    } else {
        km = null;
    }
    // Now make a truststore to verify the server
    if (this.certChain != null && this.certChain.length > 0) {
        final KeyStore trustks = KeyStore.getInstance("jks");
        trustks.load(null, "foo123".toCharArray());
        // add trusted CA cert
        trustks.setCertificateEntry("trusted", this.certChain[this.certChain.length - 1]);
        final TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
        tmf.init(trustks);
        tm = tmf.getTrustManagers();
    } else {
        tm = null;
    }
    if (km == null && tm == null) {
        return (SSLSocketFactory) SSLSocketFactory.getDefault();
    }
    final SSLContext ctx = SSLContext.getInstance("TLS");
    ctx.init(km, tm, null);

    return ctx.getSocketFactory();
}

From source file:com.vmware.bdd.security.tls.SimpleSeverTrustTlsSocketFactory.java

/**
 * factory method for custom usage./*from   w w w  .  j av  a2  s.c o  m*/
 *
 * @return a factory
 */
public static SSLSocketFactory makeSSLSocketFactory(TrustStoreConfig trustStoreCfg) {
    check(trustStoreCfg);

    SimpleServerTrustManager simpleServerTrustManager = new SimpleServerTrustManager();
    simpleServerTrustManager.setTrustStoreConfig(trustStoreCfg);
    /**
     *  Initialize our own trust manager
     */
    TrustManager[] trustManagers = new TrustManager[] { simpleServerTrustManager };

    SSLContext customSSLContext = null;
    try {
        /**
         * Instantiate a context that implements the family of TLS protocols
         */
        customSSLContext = SSLContext.getInstance("TLS");

        /**
         * Initialize SSL context. Default instances of KeyManager and
         * SecureRandom are used.
         */
        customSSLContext.init(null, trustManagers, null);
    } catch (NoSuchAlgorithmException e) {
        throw new TlsInitException("SSLContext_INIT_ERR", e);
    } catch (KeyManagementException e) {
        throw new TlsInitException("SSLContext_INIT_ERR", e);
    }

    TlsClientConfiguration tlsClientConfiguration = new TlsClientConfiguration();
    /**
     * Build connection configuration and pass to socket
     */
    SSLParameters params = new SSLParameters();
    params.setCipherSuites(tlsClientConfiguration.getCipherSuites());
    params.setProtocols(tlsClientConfiguration.getSslProtocols());
    //      params.setEndpointIdentificationAlgorithm(
    //            config.getEndpointIdentificationAlgorithm());
    /**
     * Use the SSLSocketFactory generated by the SSLContext and wrap it to
     * enable custom cipher suites and protocols
     */
    return new SimpleSeverTrustTlsSocketFactory(customSSLContext.getSocketFactory(), params);
}

From source file:org.restcomm.app.qoslib.Utils.RTWebSocket.java

private void connectWebSocket() {
    URI uri;//w  w w  . j  av a2s  . c  om
    try {
        String ws_uri = context.getString(R.string.MMC_WEBSOCKET_URL);
        uri = new URI(ws_uri);
    } catch (URISyntaxException e) {
        //e.printStackTrace();
        return;
    }

    String apiKey = context.getApiKey(context);

    HashMap<String, String> header = new HashMap<String, String>();
    header.put("apiKey", apiKey);
    mWebSocketClient = new WebSocketClient(uri, new Draft_17(), header, 10000) {
        @Override
        public void onOpen(ServerHandshake serverHandshake) {
            //Log.i("Websocket", "Opened");
            LoggerUtil.logToFile(LoggerUtil.Level.DEBUG, TAG, "connectWebSocket", "Websocket opened ");
            //mWebSocketClient.send("Hello from " + Build.MANUFACTURER + " " + Build.MODEL);
            PreferenceManager.getDefaultSharedPreferences(context).edit()
                    .putBoolean(PreferenceKeys.Miscellaneous.WEBSOCKET_RUNNING, true).commit();
            wsConnected = true;

            // Force intents to be resent for last known location, signal and cell
            context.getEventManager().signalSnapshot(null);

            context.getIntentDispatcher().updateNetwork();

        }

        @Override
        public void onMessage(String s) {
            final String message = s;

        }

        @Override
        public void onClose(int i, String s, boolean b) {
            LoggerUtil.logToFile(LoggerUtil.Level.DEBUG, TAG, "connectWebSocket", "Websocket closed " + s);

            // close web socket
            PreferenceManager.getDefaultSharedPreferences(context).edit()
                    .putBoolean(PreferenceKeys.Miscellaneous.WEBSOCKET_RUNNING, false).commit();
            mWebSocketClient = null;
            wsConnected = false;
            mWebSocketQueue.clear();
            webSocketThread = null;

        }

        @Override
        public void onError(Exception e) {
            Log.i("Websocket", "Error " + e.getMessage());
            LoggerUtil.logToFile(LoggerUtil.Level.ERROR, TAG, "connectWebSocket", "onError ", e);
        }
    };

    LoggerUtil.logToFile(LoggerUtil.Level.DEBUG, TAG, "connectWebSocket", "get SSL");
    SSLContext sslContext = null;
    try {
        sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, null, null); // will use java's default key and trust store which is sufficient unless you deal with self-signed certificates

        SSLSocketFactory factory = sslContext.getSocketFactory();// (SSLSocketFactory) SSLSocketFactory.getDefault();

        mWebSocketClient.setSocket(factory.createSocket());

        mWebSocketClient.connect();
        LoggerUtil.logToFile(LoggerUtil.Level.DEBUG, TAG, "connectWebSocket", "called connect");
    } catch (Exception e) {
        LoggerUtil.logToFile(LoggerUtil.Level.DEBUG, TAG, "connectWebSocket", "Exception: ", e);
    }
}