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.beepcore.beep.profile.tls.jsse.TLSProfileJSSE.java

/**
 * TLS provides encryption and optionally authentication for a session
 * by opening a channel with this profile.  The default action is to
 * set up for a channel with encryption only, no authentication.  To
 * mandate authentication, set the configuration via <code>init</code>.<p>
 * @see org.beepcore.beep.profile.Profile
 *//*from w  ww . j  av  a2s.  co m*/
public TLSProfileJSSE() {
    try {
        SSLContext ctx = SSLContext.getInstance("TLS");

        ctx.init(null, null, null);

        socketFactory = (SSLSocketFactory) ctx.getSocketFactory();
    } catch (NoSuchAlgorithmException e) {
        log.error(e.getMessage());
    } catch (KeyManagementException e) {
        log.error(e.getMessage());
    }

    if (handshakeListeners == null) {
        handshakeListeners = Collections.synchronizedList(new LinkedList());
    }
}

From source file:edu.duke.cabig.c3pr.webservice.integration.C3PREmbeddedTomcatTestBase.java

/**
 * Code of this method was simply Googled.
 *//*ww  w . j ava  2 s  .  com*/
void disableSSLVerification() {
    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) {
        }
    } };

    try {
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (Exception e) {
        e.printStackTrace();
    }

    com.sun.net.ssl.HostnameVerifier hv = new com.sun.net.ssl.HostnameVerifier() {

        public boolean verify(String urlHostname, String certHostname) {
            return true;
        }
    };
    com.sun.net.ssl.HttpsURLConnection.setDefaultHostnameVerifier(hv);

    HostnameVerifier hv2 = new HostnameVerifier() {

        public boolean verify(String urlHostName, SSLSession session) {
            return true;
        }
    };
    HttpsURLConnection.setDefaultHostnameVerifier(hv2);

}

From source file:org.whispersystems.signalservice.internal.push.PushServiceSocket.java

private Response getConnection(String urlFragment, String method, String body) throws PushNetworkException {
    try {/*from   ww  w  . j  av a  2  s .c o  m*/
        Log.w(TAG, "Push service URL: " + serviceUrl.getUrl());
        Log.w(TAG, "Opening URL: " + String.format("%s%s", serviceUrl.getUrl(), urlFragment));

        SSLContext context = SSLContext.getInstance("TLS");
        context.init(null, trustManagers, null);

        OkHttpClient okHttpClient = new OkHttpClient();
        okHttpClient.setSslSocketFactory(context.getSocketFactory());
        okHttpClient.setHostnameVerifier(new StrictHostnameVerifier());

        Request.Builder request = new Request.Builder();
        request.url(String.format("%s%s", serviceUrl.getUrl(), urlFragment));

        if (body != null) {
            request.method(method, RequestBody.create(MediaType.parse("application/json"), body));
        } else {
            request.method(method, null);
        }

        if (credentialsProvider.getPassword() != null) {
            request.addHeader("Authorization", getAuthorizationHeader());
        }

        if (userAgent != null) {
            request.addHeader("X-Signal-Agent", userAgent);
        }

        if (serviceUrl.getHostHeader().isPresent()) {
            okHttpClient.networkInterceptors().add(new HostInterceptor(serviceUrl.getHostHeader().get()));
        }

        return okHttpClient.newCall(request.build()).execute();
    } catch (IOException e) {
        throw new PushNetworkException(e);
    } catch (NoSuchAlgorithmException | KeyManagementException e) {
        throw new AssertionError(e);
    }
}

From source file:it.infn.ct.downtime.Downtime.java

@Override
protected void doView(RenderRequest request, RenderResponse response) throws PortletException, IOException {
    try {//from  w w w  . j  av a  2  s  . c o  m
        PortletPreferences portletPreferences = (PortletPreferences) request.getPreferences();

        response.setContentType("text/html");

        PortletRequestDispatcher dispatcher = null;
        String[] downtime_endpoints = new String[15];

        String downtime_REFRESH = portletPreferences.getValue("downtime_REFRESH", "1440000");
        String downtime_LOGLEVEL = portletPreferences.getValue("downtime_LOGLEVEL", "INFO");
        downtime_endpoints = portletPreferences.getValues("downtime_endpoints", new String[15]);
        String downtime_IDs = portletPreferences.getValue("downtime_IDs", "-1");
        String SMTP_HOST = portletPreferences.getValue("SMTP_HOST", "N/A");
        String SENDER_MAIL = portletPreferences.getValue("SENDER_MAIL", "N/A");

        File df_full = new File("/tmp/full_report.xml");
        File df = null;
        BufferedReader bufReader = null;
        String endpoints = "";
        boolean flag = false;

        // Create a file containing all the downtimes.
        FileWriter fileWritter = new FileWriter(df_full, false);
        BufferedWriter bufferWritter = new BufferedWriter(fileWritter);

        String header = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
        String results_tag_start = "<results>";
        String results_tag_end = "</results>";

        bufferWritter.write(header + "\n");
        bufferWritter.write(results_tag_start + "\n");

        for (int i = 0; i < downtime_endpoints.length; i++) {
            if (downtime_endpoints[i] != null && !downtime_endpoints[i].isEmpty()) {
                SSLContext sc = SSLContext.getInstance("SSL");
                sc.init(null, trustAllCerts, new java.security.SecureRandom());

                HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

                String downtime_url = "https://goc.egi.eu/gocdbpi/public/"
                        + "?method=get_downtime_nested_services" + "&topentity=" + downtime_endpoints[i]
                        + "&page=1&ongoing_only=yes";

                log.info("GOC-DB endpoint: " + downtime_url);

                // Get the list of ongoing downtime
                URL url = new URL(downtime_url);
                try {
                    df = File.createTempFile("result_", ".xml");

                    org.apache.commons.io.FileUtils.copyURLToFile(url, df);
                    log.info("File: " + df.getAbsolutePath());

                    // our XML file for this example
                    File xmlFile = new File(df.getAbsolutePath());
                    Reader fileReader = new FileReader(xmlFile);
                    bufReader = new BufferedReader(fileReader);

                    StringBuilder sb = new StringBuilder();
                    // Skip the first 2 rows
                    bufReader.readLine();
                    bufReader.readLine();

                    String line = bufReader.readLine();
                    while (line != null) {
                        if ((!line.contains("results")))
                            sb.append(line).append("\n");

                        line = bufReader.readLine();
                    }

                    String xml2String = sb.toString();
                    if (xml2String != null && !xml2String.isEmpty()) {
                        log.info("XML to String using BufferedReader: ");
                        log.info(xml2String);

                        bufferWritter.write(xml2String);

                        flag = true;
                    }

                    bufReader.close();
                    df.deleteOnExit();

                } catch (IOException ex) {
                    log.error(ex);
                } finally {
                    df.delete();
                }
            }
        }

        bufferWritter.write(results_tag_end + "\n");
        bufferWritter.close();

        boolean sending = false;
        if (flag) {
            //request.setAttribute("downtime_IDs", getIDs(df_full));

            // Store the new IDs in the portlet preferences
            if (downtime_IDs.equals("-1")) {
                portletPreferences.setValue("downtime_IDs", getIDs(df_full));
                sending = true; // enable the notification
            } else {
                String[] array1 = getIDs(df_full).split(",");
                String[] array2 = downtime_IDs.trim().split(",");

                log.info("XML = " + Arrays.toString(array1));
                log.info("Preferences = " + Arrays.toString(array2));

                String ids = "";
                String[] list = getIntersection(array1, array2);
                for (String id : list)
                    ids += id + ",";

                // Check if we need to add new IDs and remove old ones
                for (int i1 = 0; i1 < array1.length; i1++) {
                    if (!ids.contains(array1[i1])) {
                        ids += array1[i1] + ",";
                        sending = true; // enable the notification
                    }
                }

                List<String> listwithduplicate = new ArrayList<String>(Arrays.asList(ids));

                Set<String> s = new LinkedHashSet<String>(listwithduplicate);
                //log.info("ids(after)= " + s);

                log.info("Preferences to store = " + ids.substring(0, ids.length() - 1));
                portletPreferences.setValue("downtime_IDs", ids.substring(0, ids.length() - 1));
            }

            // Get list of users in Liferay
            int countUser = UserLocalServiceUtil.getUsersCount();
            List<User> users = UserLocalServiceUtil.getUsers(0, countUser);
            for (User liferay_user : users) {
                /*log.info("UserID = " + liferay_user.getUserId() 
                + " UserCompanyID = " + liferay_user.getCompanyId() 
                + " UserEmail = " + liferay_user.getEmailAddress() 
                + " UserScreenName = " + liferay_user.getScreenName());*/

                if (sending) {
                    if ((SMTP_HOST == null) || (SMTP_HOST.trim().equals("")) || (SMTP_HOST.trim().equals("N/A"))
                            || (SENDER_MAIL == null) || (SENDER_MAIL.trim().equals(""))
                            || (SENDER_MAIL.trim().equals("N/A")))
                        log.info("\nThe Notification Service is not properly configured!!");

                    else {
                        log.info("\nSending notification to the user [ OK ]");
                        sendHTMLEmail(liferay_user.getEmailAddress(), SENDER_MAIL, SMTP_HOST, df_full);
                    }
                }
            }
        } else {
            // Recover original setting.
            portletPreferences.setValue("downtime_IDs", "-1");
        }

        // Save the portlet preferences
        request.setAttribute("downtime_REFRESH", downtime_REFRESH.trim());
        request.setAttribute("downtime_LOGLEVEL", downtime_LOGLEVEL.trim());
        request.setAttribute("downtime_endpoints", endpoints);
        request.setAttribute("SMTP_HOST", SMTP_HOST.trim());
        request.setAttribute("SENDER_MAIL", SENDER_MAIL.trim());
        request.setAttribute("DOWNTIME_XML", df_full.toString().trim());

        // Storing the preferences
        portletPreferences.store();

        dispatcher = getPortletContext().getRequestDispatcher("/view.jsp");
        dispatcher.include(request, response);

    } catch (SystemException ex) {
        Logger.getLogger(Downtime.class.getName()).log(Level.SEVERE, null, ex);
    } catch (KeyManagementException ex) {
        Logger.getLogger(Downtime.class.getName()).log(Level.SEVERE, null, ex);
    } catch (NoSuchAlgorithmException ex) {
        Logger.getLogger(Downtime.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:be.fedict.eid.idp.sp.protocol.saml2.artifact.ArtifactServiceClient.java

/**
 * If set, unilateral TLS authentication will occur, verifying the server
 * {@link X509Certificate} specified against the {@link PublicKey}.
 * // www  .j a  va 2s.  c o  m
 * @param publicKey
 *            public key to validate server TLS certificate against.
 */
public void setServicePublicKey(final PublicKey publicKey) {

    // Create TrustManager
    TrustManager[] trustManager = { new X509TrustManager() {

        public X509Certificate[] getAcceptedIssuers() {

            return null;
        }

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

            X509Certificate serverCertificate = chain[0];
            LOG.debug("server X509 subject: " + serverCertificate.getSubjectX500Principal().toString());
            LOG.debug("authentication type: " + authType);
            if (null == publicKey) {
                return;
            }

            try {
                serverCertificate.verify(publicKey);
                LOG.debug("valid server certificate");
            } catch (InvalidKeyException e) {
                throw new CertificateException("Invalid Key");
            } catch (NoSuchAlgorithmException e) {
                throw new CertificateException("No such algorithm");
            } catch (NoSuchProviderException e) {
                throw new CertificateException("No such provider");
            } catch (SignatureException e) {
                throw new CertificateException("Wrong signature");
            }
        }

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

            throw new CertificateException("this trust manager cannot be used as server-side trust manager");
        }
    } };

    // Create SSL Context
    try {
        SSLContext sslContext = SSLContext.getInstance("TLS");
        SecureRandom secureRandom = new SecureRandom();
        sslContext.init(null, trustManager, secureRandom);
        LOG.debug("SSL context provider: " + sslContext.getProvider().getName());

        // Setup TrustManager for validation
        Map<String, Object> requestContext = ((BindingProvider) this.port).getRequestContext();
        requestContext.put(JAXWSProperties.SSL_SOCKET_FACTORY, sslContext.getSocketFactory());

    } catch (KeyManagementException e) {
        String msg = "key management error: " + e.getMessage();
        LOG.error(msg, e);
        throw new RuntimeException(msg, e);
    } catch (NoSuchAlgorithmException e) {
        String msg = "TLS algo not present: " + e.getMessage();
        LOG.error(msg, e);
        throw new RuntimeException(msg, e);
    }
}

From source file:org.eclipse.smarthome.io.transport.mqtt.internal.MqttBrokerConnection.java

/**
 * Open an MQTT client connection./*from w w w  .ja  va2s .  c o  m*/
 * 
 * @throws Exception
 */
private void openConnection() throws Exception {

    try {
        if (client != null && client.isConnected()) {
            return;
        }

        if (StringUtils.isBlank(url)) {
            throw new Exception("Missing url.");
        }

        if (client == null) {
            if (StringUtils.isBlank(clientId) || clientId.length() > 23) {
                clientId = MqttClient.generateClientId();
            }

            String tmpDir = System.getProperty("java.io.tmpdir");
            MqttDefaultFilePersistence dataStore = new MqttDefaultFilePersistence(tmpDir + "/" + name);
            logger.debug("Creating new client for '{}' using id '{}' and file store '{}'",
                    new Object[] { url, clientId, tmpDir + "/" + name });
            client = new MqttClient(url, clientId, dataStore);
            client.setCallback(this);
        }

        MqttConnectOptions options = new MqttConnectOptions();

        if (!StringUtils.isBlank(user)) {
            options.setUserName(user);
        }
        if (!StringUtils.isBlank(password)) {
            options.setPassword(password.toCharArray());
        }
        if (url.toLowerCase().contains("ssl")) {

            if (StringUtils.isNotBlank(System.getProperty("com.ibm.ssl.protocol"))) {

                // get all com.ibm.ssl properties from the system properties
                // and set them as the SSL properties to use.

                Properties sslProps = new Properties();
                addSystemProperty("com.ibm.ssl.protocol", sslProps);
                addSystemProperty("com.ibm.ssl.contextProvider", sslProps);
                addSystemProperty("com.ibm.ssl.keyStore", sslProps);
                addSystemProperty("com.ibm.ssl.keyStorePassword", sslProps);
                addSystemProperty("com.ibm.ssl.keyStoreType", sslProps);
                addSystemProperty("com.ibm.ssl.keyStoreProvider", sslProps);
                addSystemProperty("com.ibm.ssl.trustStore", sslProps);
                addSystemProperty("com.ibm.ssl.trustStorePassword", sslProps);
                addSystemProperty("com.ibm.ssl.trustStoreType", sslProps);
                addSystemProperty("com.ibm.ssl.trustStoreProvider", sslProps);
                addSystemProperty("com.ibm.ssl.enabledCipherSuites", sslProps);
                addSystemProperty("com.ibm.ssl.keyManager", sslProps);
                addSystemProperty("com.ibm.ssl.trustManager", sslProps);

                options.setSSLProperties(sslProps);

            } else {

                // use standard JSSE available in the runtime and 
                // use TLSv1.2 which is the default for a secured mosquitto
                SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
                sslContext.init(null, new TrustManager[] { getVeryTrustingTrustManager() },
                        new java.security.SecureRandom());
                SSLSocketFactory socketFactory = sslContext.getSocketFactory();
                options.setSocketFactory(socketFactory);
            }
        }

        client.connect(options);

    } catch (MqttException e) {
        logger.error("Error connecting to broker '{}' : {} : ReasonCode {} : Cause : {}",
                new Object[] { name, e.getMessage(), e.getReasonCode(), e.getCause().getMessage() });
        throw e;
    }

}

From source file:edu.indiana.d2i.registryext.RegistryExtAgent.java

private boolean disableSSL() {
    // Create empty HostnameVerifier
    HostnameVerifier hv = new HostnameVerifier() {
        public boolean verify(String urlHostName, SSLSession session) {
            return true;
        }//  w  ww. java  2  s.  co m
    };

    // 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 all-trust manager
    try {
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        SSLSocketFactory sslSocketFactory = sc.getSocketFactory();
        HttpsURLConnection.setDefaultSSLSocketFactory(sslSocketFactory);
        HttpsURLConnection.setDefaultHostnameVerifier(hv);
        return true;
    } catch (NoSuchAlgorithmException e) {
        logger.error(e.getMessage(), e);
        return false;
    } catch (KeyManagementException e) {
        logger.error(e.getMessage(), e);
        return false;
    }
}

From source file:org.openhab.io.transport.mqtt.internal.MqttBrokerConnection.java

/**
 * Open an MQTT client connection./*w ww.  j av  a  2  s  . c om*/
 * 
 * @throws Exception
 */
private void openConnection() throws Exception {
    if (client != null && client.isConnected()) {
        return;
    }

    if (StringUtils.isBlank(url)) {
        throw new Exception("Missing url");
    }

    if (client == null) {
        if (StringUtils.isBlank(clientId) || clientId.length() > 23) {
            clientId = MqttClient.generateClientId();
        }

        String tmpDir = System.getProperty("java.io.tmpdir") + "/" + name;
        MqttDefaultFilePersistence dataStore = new MqttDefaultFilePersistence(tmpDir);
        logger.debug("Creating new client for '{}' using id '{}' and file store '{}'", url, clientId, tmpDir);
        client = new MqttClient(url, clientId, dataStore);
        client.setCallback(this);
    }

    MqttConnectOptions options = new MqttConnectOptions();

    if (!StringUtils.isBlank(user)) {
        options.setUserName(user);
    }
    if (!StringUtils.isBlank(password)) {
        options.setPassword(password.toCharArray());
    }
    if (url.toLowerCase().contains("ssl")) {

        if (StringUtils.isNotBlank(System.getProperty("com.ibm.ssl.protocol"))) {

            // get all com.ibm.ssl properties from the system properties
            // and set them as the SSL properties to use.

            Properties sslProps = new Properties();
            addSystemProperty("com.ibm.ssl.protocol", sslProps);
            addSystemProperty("com.ibm.ssl.contextProvider", sslProps);
            addSystemProperty("com.ibm.ssl.keyStore", sslProps);
            addSystemProperty("com.ibm.ssl.keyStorePassword", sslProps);
            addSystemProperty("com.ibm.ssl.keyStoreType", sslProps);
            addSystemProperty("com.ibm.ssl.keyStoreProvider", sslProps);
            addSystemProperty("com.ibm.ssl.trustStore", sslProps);
            addSystemProperty("com.ibm.ssl.trustStorePassword", sslProps);
            addSystemProperty("com.ibm.ssl.trustStoreType", sslProps);
            addSystemProperty("com.ibm.ssl.trustStoreProvider", sslProps);
            addSystemProperty("com.ibm.ssl.enabledCipherSuites", sslProps);
            addSystemProperty("com.ibm.ssl.keyManager", sslProps);
            addSystemProperty("com.ibm.ssl.trustManager", sslProps);

            options.setSSLProperties(sslProps);

        } else {

            // use standard JSSE available in the runtime and
            // use TLSv1.2 which is the default for a secured mosquitto
            SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
            sslContext.init(null, new TrustManager[] { getVeryTrustingTrustManager() },
                    new java.security.SecureRandom());
            SSLSocketFactory socketFactory = sslContext.getSocketFactory();
            options.setSocketFactory(socketFactory);
        }
    }

    if (lastWill != null) {
        options.setWill(lastWill.getTopic(), lastWill.getPayload(), lastWill.getQos(), lastWill.isRetain());
    }

    options.setKeepAliveInterval(keepAliveInterval);

    client.connect(options);
}

From source file:gov.nih.nci.nbia.StandaloneDMDispatcher.java

private void downloadInstaller(String downloadUrl) {
    String fileName = getInstallerName(downloadUrl);
    InputStream in;/*from   www  .jav a 2 s  .c o  m*/

    // 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(X509Certificate[] certs, String authType) {
            // here is the place to check client certs and throw an
            // exception if certs are wrong. When there is nothing all certs
            // accepted.
        }

        public void checkServerTrusted(X509Certificate[] certs, String authType) {
            // here is the place to check server certs and throw an
            // exception if certs are wrong. When there is nothing all certs
            // accepted.
        }
    } };
    // Install the all-trusting trust manager
    try {
        final SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

        // Create all-trusting host name verifier
        HostnameVerifier allHostsValid = new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                // Here is the palce to check host name against to
                // certificate owner
                return true;
            }
        };
        // Install the all-trusting host verifier
        HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
    } catch (KeyManagementException | NoSuchAlgorithmException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } finally {
    }

    try {
        URL url = new URL(downloadUrl);
        in = url.openStream();
        FileOutputStream fos = new FileOutputStream(new File(fileName));

        int length = -1;
        ProgressMonitorInputStream pmis;
        pmis = new ProgressMonitorInputStream(null,
                "Downloading new version of installer for NBIA Data Retriever...", in);

        ProgressMonitor monitor = pmis.getProgressMonitor();
        monitor.setMillisToPopup(0);
        monitor.setMinimum(0);
        monitor.setMaximum((int) 200000000); // The actual size is much
        // smaller,
        // but we have no way to
        // know
        // the actual size so picked
        // this big number

        byte[] buffer = new byte[1024];// buffer for portion of data from
        // connection

        while ((length = pmis.read(buffer)) > 0) {
            fos.write(buffer, 0, length);
        }
        pmis.close();
        fos.flush();
        fos.close();
        in.close();

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:com.ds.kaixin.Kaixin.java

private Kaixin() {
    System.setProperty("http.keepAlive", "false");

    SSLContext sslContext = null;

    try {/*from   www . j  a v  a 2 s .  c o m*/
        sslContext = SSLContext.getInstance("TLS");
        X509TrustManager[] xtmArray = new X509TrustManager[] { xtm };
        sslContext.init(null, xtmArray, new java.security.SecureRandom());
    } catch (GeneralSecurityException gse) {
    }
    if (sslContext != null) {
        HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
    }

    HttpsURLConnection.setDefaultHostnameVerifier(hnv);
}