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.inovex.zabbixmobile.activities.BaseActivity.java

/**
 * Binds the data service and sets up the action bar.
 *///  w  ww  . ja  v  a  2 s  . c  om
@Override
protected void onCreate(Bundle savedInstanceState) {
    ZaxPreferences prefs = ZaxPreferences.getInstance(getApplicationContext());
    if (prefs.isDarkTheme())
        setTheme(R.style.AppThemeDark);
    else
        setTheme(R.style.AppTheme);
    super.onCreate(savedInstanceState);

    finishReceiver = new FinishReceiver();
    registerReceiver(finishReceiver, new IntentFilter(ACTION_FINISH));

    bindService();

    // (re-) instantiate progress dialog
    mLoginProgress = (LoginProgressDialogFragment) getSupportFragmentManager()
            .findFragmentByTag(LoginProgressDialogFragment.TAG);

    if (mLoginProgress == null) {
        mLoginProgress = LoginProgressDialogFragment.getInstance();
    }

    try {
        SSLContext sc = SSLContext.getInstance("TLS");
        MemorizingTrustManager mtm = new MemorizingTrustManager(this);
        sc.init(null, new X509TrustManager[] { mtm }, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        HttpsURLConnection.setDefaultHostnameVerifier(
                mtm.wrapHostnameVerifier(HttpsURLConnection.getDefaultHostnameVerifier()));
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (KeyManagementException e) {
        e.printStackTrace();
    }
}

From source file:com.telesign.util.TeleSignRequest.java

/**
 * Set the TLS protocol to TLSv1.2//from w w w  . j a v  a  2s .  c o m
 */
private void setTLSProtocol() {
    SSLContext sslContext;
    try {
        // setting ssl instance to TLSv1.x
        sslContext = SSLContext.getInstance(httpsProtocol);

        // sslContext initialize
        sslContext.init(null, null, new SecureRandom());

        // typecasting ssl with HttpsUrlConnection and setting sslcontext
        ((HttpsURLConnection) connection).setSSLSocketFactory(sslContext.getSocketFactory());
    } catch (NoSuchAlgorithmException e1) {
        System.err.println("Received No Such Alogorithm Exception " + e1.getMessage());
    } catch (KeyManagementException e) {
        System.err.println("Key Management Exception received " + e.getMessage());
    }
}

From source file:org.apache.nifi.processors.standard.TestListenTCP.java

protected void runTCP(final List<String> messages, final int expectedTransferred, final SSLContext sslContext)
        throws IOException, InterruptedException {

    Socket socket = null;//from   w w w . ja v  a  2s .c o m
    try {
        // schedule to start listening on a random port
        final ProcessSessionFactory processSessionFactory = runner.getProcessSessionFactory();
        final ProcessContext context = runner.getProcessContext();
        proc.onScheduled(context);

        // create a client connection to the port the dispatcher is listening on
        final int realPort = proc.getDispatcherPort();

        // create either a regular socket or ssl socket based on context being passed in
        if (sslContext != null) {
            socket = sslContext.getSocketFactory().createSocket("localhost", realPort);
        } else {
            socket = new Socket("localhost", realPort);
        }
        Thread.sleep(100);

        // send the frames to the port the processors is listening on
        for (final String message : messages) {
            socket.getOutputStream().write(message.getBytes(StandardCharsets.UTF_8));
            Thread.sleep(1);
        }
        socket.getOutputStream().flush();

        long responseTimeout = 10000;

        // this first loop waits until the internal queue of the processor has the expected
        // number of messages ready before proceeding, we want to guarantee they are all there
        // before onTrigger gets a chance to run
        long startTimeQueueSizeCheck = System.currentTimeMillis();
        while (proc.getQueueSize() < messages.size()
                && (System.currentTimeMillis() - startTimeQueueSizeCheck < responseTimeout)) {
            Thread.sleep(100);
        }

        // want to fail here if the queue size isn't what we expect
        Assert.assertEquals(messages.size(), proc.getQueueSize());

        // call onTrigger until we processed all the frames, or a certain amount of time passes
        int numTransferred = 0;
        long startTime = System.currentTimeMillis();
        while (numTransferred < expectedTransferred
                && (System.currentTimeMillis() - startTime < responseTimeout)) {
            proc.onTrigger(context, processSessionFactory);
            numTransferred = runner.getFlowFilesForRelationship(ListenTCP.REL_SUCCESS).size();
            Thread.sleep(100);
        }

        // should have transferred the expected events
        runner.assertTransferCount(ListenTCP.REL_SUCCESS, expectedTransferred);
    } finally {
        // unschedule to close connections
        proc.onUnscheduled();
        IOUtils.closeQuietly(socket);
    }
}

From source file:com.cttapp.bby.mytlc.layer8apps.SimpleSSLSocketFactory.java

public SimpleSSLSocketFactory(KeyStore truststore)
        throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
    super(null);//from  ww  w .j a v a 2  s.  co  m

    try {
        SSLContext context = SSLContext.getInstance("TLS");

        // Create a trust manager that does not validate certificate chains and simply
        // accept all type of certificates
        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 {
            }
        } };

        // Initialize the socket factory
        context.init(null, trustAllCerts, new SecureRandom());
        sslFactory = context.getSocketFactory();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.androidinahurry.network.utils.FakeSSLSocketFactory.java

public FakeSSLSocketFactory(KeyStore truststore)
        throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
    super(null);/*  w  w w.j a  v a 2  s  .  c o m*/

    try {
        SSLContext context = SSLContext.getInstance("TLS");

        // Create a trust manager that does not validate certificate chains
        // and simply
        // accept all type of certificates
        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 {
            }
        } };

        // Initialize the socket factory
        context.init(null, trustAllCerts, new SecureRandom());
        sslFactory = context.getSocketFactory();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.isecpartners.gizmo.HttpRequest.java

private synchronized SSLSocketFactory initSSL(String hostname)
        throws KeyStoreException, NoSuchAlgorithmException, CertificateException, UnrecoverableKeyException,
        IOException, KeyManagementException, InvalidKeyException, SignatureException, NoSuchProviderException,
        NoCertException {// www  . j av a 2 s  . c  o  m

    KeyManagerFactory kmf = null;
    SSLContext sslcontext = null;

    kmf = createKeyManagerFactory(hostname);
    sslcontext = SSLContext.getInstance("SSLv3", Security.getProvider("BC"));
    sslcontext.init(kmf.getKeyManagers(), null, null);
    SSLSocketFactory factory = sslcontext.getSocketFactory();

    _factories.put(hostname, factory);
    return factory;

}

From source file:com.chaosinmotion.securechat.messages.SCMessageQueue.java

/**
 * The back end is advertising an endpoint we can connect to for
 * asynchronous networking. Attempt to open a connection. Note that
 * this must be kicked off in a background thread.
 *///  ww  w  .  j  a v  a2s.  c  o  m

private void openConnection(String host, int port, boolean ssl)
        throws NoSuchAlgorithmException, KeyManagementException, IOException, JSONException {
    if (ssl) {
        TrustManager acceptAllTrustManager = 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];
            }
        };
        TrustManager[] tm = new TrustManager[] { acceptAllTrustManager };
        SSLContext context = SSLContext.getInstance("TLS");
        context.init(new KeyManager[0], tm, new SecureRandom());

        SSLSocketFactory factory = context.getSocketFactory();

        socket = factory.createSocket(host, port);
    } else {
        socket = new Socket(host, port);
    }

    /*
     *  Kick off an output stream
     */

    output = new SCOutputStream(socket.getOutputStream());

    /*
     *  Kick off a thread to process the input stream
     */

    Thread thread = new Thread() {
        @Override
        public void run() {
            try {
                input = new SCInputStream(socket.getInputStream()) {
                    @Override
                    public void processPacket(byte[] data) {
                        processDataPacket(data);
                    }
                };
                input.processStream();
                input.close();

                /*
                 *  When the input closes, we simply quit the thread.
                 *  TODO: I'm not sure if that's the correct answer.
                 */
            } catch (final Exception ex) {
                ThreadPool.get().enqueueMain(new Runnable() {
                    @Override
                    public void run() {
                        startPolling("Unknown exception " + ex.getMessage());
                        Log.d("SecureChat", "Exception while opening socket", ex);
                    }
                });
            }
        }
    };
    thread.start();

    /*
     *   Now the first packet we need to send to the writer (and our
     *   output stream will cache this) is a JSON request to log in.
     *
     *   On the off chance logging in fails, the back end will simply
     *   close the connection.
     *
     *   Because there is no one-to-one (in theory) of data sent and
     *   received, we drive this through a state machine.
     */

    JSONObject obj = new JSONObject();
    obj.put("cmd", "token");
    byte[] data = obj.toString().getBytes("UTF-8");
    output.writeData(data);
}

From source file:com.microfocus.application.automation.tools.srf.run.RunFromSrfBuilder.java

@Override
public boolean perform(final AbstractBuild<?, ?> build, final Launcher launcher, BuildListener _listener)
        throws InterruptedException, IOException {

    this.logger = _listener.getLogger();
    Dispatcher.TRACE = true;//from   ww w .ja  v a  2  s.  co  m
    Dispatcher.TRACE_PER_REQUEST = true;

    this._token = null; // Important in order to get only this run events
    this.build = build;
    this.sseEventListener = new SseEventListener(this.logger);
    this.sseEventListener.addObserver(this);
    this.srfExecutionFuture = new CompletableFuture<>();
    this.runningCount = new HashSet<>();

    JSONObject conData = getSrfConnectionData(build, logger);
    if (conData == null)
        return false;

    _app = conData.getString("app");
    _secret = conData.getString("secret");
    _ftaasServerAddress = conData.getString("server");
    _https = conData.getBoolean("https");
    _tenant = conData.getString("tenant");
    String srfProxy = conData.getString("proxy");

    URL proxy = null;
    if ((srfProxy != null) && (srfProxy.length() != 0)) {
        proxy = new URL(srfProxy);
        String proxyHost = proxy.getHost();
        String proxyPort = String.format("%d", proxy.getPort());
        Properties systemProperties = System.getProperties();
        systemProperties.setProperty("https.proxyHost", proxyHost);
        systemProperties.setProperty("http.proxyHost", proxyHost);
        systemProperties.setProperty("https.proxyPort", proxyPort);
        systemProperties.setProperty("http.proxyPort", proxyPort);
    }

    try {
        SSLContext sslContext = SSLContext.getInstance("TLS");
        _trustMgr = new SrfTrustManager();
        sslContext.init(null, new SrfTrustManager[] { _trustMgr }, null);
        SSLContext.setDefault(sslContext);
        _factory = sslContext.getSocketFactory();
        this.srfClient = new SrfClient(_ftaasServerAddress, _tenant, _factory, proxy);
    } catch (NoSuchAlgorithmException | KeyManagementException e) {
        logger.print(e.getMessage());
        logger.print("\n\r");
    }

    jobIds = null;
    try {
        srfClient.login(_app, _secret);
        this._token = srfClient.getAccessToken();

        initSrfEventListener();
        jobIds = executeTestsSet();

    } catch (UnknownHostException | ConnectException | SSLHandshakeException | IllegalArgumentException
            | AuthorizationException | AuthenticationException e) {
        cleanUp();
        logger.println(
                String.format("ERROR: Failed logging into SRF server: %s %s", this._ftaasServerAddress, e));
        return false;
    } catch (IOException | SrfException e) {
        cleanUp();
        logger.println(String.format("ERROR: Failed executing test, %s", e));
        return false;
    }

    try {
        boolean buildResult = this.srfExecutionFuture.get();
        return buildResult;
    } catch (ExecutionException e) {
        e.printStackTrace();
        return false;
    } catch (InterruptedException e) {
        e.printStackTrace();
        build.setResult(Result.ABORTED);
        // TODO: Optimization instead of testrunid set maintain testrunid map with job info, in order to avoid already finished job cancellation
        if (!jobIds.isEmpty()) {
            for (int i = 0; i < jobIds.size(); i++) {
                String jobId = jobIds.get(i).toString();
                try {
                    srfClient.cancelJob(jobId);
                } catch (SrfException e1) {
                    e1.printStackTrace();
                }
            }
        }

        return false;
    } finally {
        cleanUp();
    }
}

From source file:com.dynatrace.license.count.monitor.counter.java

public void disableCertificateValidation() {
    log.finer("Entering disableCertificateValidation method");
    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0];
        }// ww  w .  j  av  a  2s. c  o m

        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 hostname, SSLSession session) {
            return true;
        }
    };

    // Install the all-trusting trust manager
    try {
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        HttpsURLConnection.setDefaultHostnameVerifier(hv);
    } catch (Exception e) {
    }

    log.finer("Exiting disableCertificateValidation method");
}

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

public SSLSocketFactory getClientSocketFactory(String type) {
    // Trust all invalid server certificate
    TrustManager[] trustMgr = new TrustManager[] { new RelaxedX509TrustManager() };

    try {//from   w  w  w.  ja  va 2  s . com
        SSLContext sslContext = SSLContext.getInstance(type);
        java.security.SecureRandom x = new java.security.SecureRandom();
        x.setSeed(System.currentTimeMillis());
        if (relaxedTrust) {
            sslContext.init(null, trustMgr, x);
        } else {
            sslContext.init(null, null, x);
        }
        clientSSLSockFactory = createDecoratedClientSslSocketFactory(sslContext.getSocketFactory());
        HttpsURLConnection.setDefaultSSLSocketFactory(clientSSLSockFactory);

    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    }

    return clientSSLSockFactory;

}