Example usage for javax.net.ssl SSLSocketFactory createSocket

List of usage examples for javax.net.ssl SSLSocketFactory createSocket

Introduction

In this page you can find the example usage for javax.net.ssl SSLSocketFactory createSocket.

Prototype

@Override
    public Socket createSocket(InetAddress address, int port) throws IOException 

Source Link

Usage

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.
 *//*from w  ww  . j av 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.photon.phresco.framework.rest.api.util.FrameworkServiceUtil.java

public static List<CertificateInfo> getCertificate(String host, int port) throws PhrescoException {
    List<CertificateInfo> certificates = new ArrayList<CertificateInfo>();
    CertificateInfo info;//  w  ww.j  ava 2s  .c o m
    try {
        KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
        SSLContext context = SSLContext.getInstance("TLS");
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(ks);
        X509TrustManager defaultTrustManager = (X509TrustManager) tmf.getTrustManagers()[0];
        SavingTrustManager tm = new SavingTrustManager(defaultTrustManager);
        context.init(null, new TrustManager[] { tm }, null);
        SSLSocketFactory factory = context.getSocketFactory();
        SSLSocket socket = (SSLSocket) factory.createSocket(host, port);
        socket.setSoTimeout(10000);
        try {
            socket.startHandshake();
            socket.close();
        } catch (SSLException e) {

        }
        X509Certificate[] chain = tm.chain;
        for (int i = 0; i < chain.length; i++) {
            X509Certificate x509Certificate = chain[i];
            String subjectDN = x509Certificate.getSubjectDN().getName();
            String[] split = subjectDN.split(",");
            info = new CertificateInfo();
            info.setSubjectDN(subjectDN);
            info.setDisplayName(split[0]);
            info.setCertificate(x509Certificate);
            certificates.add(info);
        }
    } catch (Exception e) {
        throw new PhrescoException(e);
    }
    return certificates;
}

From source file:me.mneri.rice.Connection.java

public void start() {
    if (mState != State.CLOSED)
        return;/*from   w w w.  j a  v a 2s.  c o m*/

    mState = State.STARTED;
    emit(new Event(START, this));

    new Thread(() -> {
        try {
            if (mSecure) {
                SSLContext sslContext = SSLContext.getInstance("TLS");
                String algorithm = TrustManagerFactory.getDefaultAlgorithm();
                TrustManagerFactory tmFactory = TrustManagerFactory.getInstance(algorithm);
                tmFactory.init((KeyStore) null);
                sslContext.init(null, tmFactory.getTrustManagers(), null);
                SSLSocketFactory sslFactory = sslContext.getSocketFactory();
                SSLSocket sslSocket = (SSLSocket) sslFactory.createSocket(mHost, mPort);
                sslSocket.startHandshake();
                mSocket = sslSocket;
            } else {
                mSocket = new Socket(mHost, mPort);
            }

            mSocket.setSoTimeout(mSoTimeout);
            mInputThread = new InputThread(mSocket.getInputStream(), mEncoding, new InputThreadObserver());
            mInputThread.start();
            OutputInterfaceFactory outFactory = OutputInterfaceFactory.instance();
            OutputStreamWriter outWriter = new OutputStreamWriter(mSocket.getOutputStream(), mEncoding);
            mOutputInterface = outFactory.createInterface(outWriter);

            mState = State.CONNECTED;
            emit(new Event(CONNECT, this));
            cap("LS");

            if (!TextUtils.isEmpty(mPass))
                pass(mPass);

            nick(mWantedNick);
            user(mUser, mLoginMode, "*", mReal);
        } catch (Exception e) {
            onDisconnection();
        }
    }).start();
}

From source file:iracing.webapi.IracingWebApi.java

private void installCerts() throws Exception {
    String host = "members.iracing.com";
    int port = 443;

    char[] password = CERT_STORE_PASSWORD.toCharArray();

    File file = new File("jssecacerts");
    if (!file.isFile()) {
        char seperator = File.separatorChar;
        File dir = new File(System.getProperty("java.home") + seperator + "lib" + seperator + "security");
        file = new File(dir, "jssecacerts");
        if (!file.isFile()) {
            file = new File(dir, "cacerts");
        }/*from  ww w.jav  a  2 s . c om*/
    }
    KeyStore ks;
    InputStream in = new FileInputStream(file);
    ks = KeyStore.getInstance(KeyStore.getDefaultType());
    try {
        ks.load(in, password);
    } catch (Exception e) {
    }
    in.close();

    SSLContext context = SSLContext.getInstance("TLS");
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(ks);
    X509TrustManager defaultTrustManager = (X509TrustManager) tmf.getTrustManagers()[0];
    SavingTrustManager tm = new SavingTrustManager(defaultTrustManager);
    context.init(null, new TrustManager[] { tm }, null);
    SSLSocketFactory factory = context.getSocketFactory();

    SSLSocket socket = null;
    try {
        socket = (SSLSocket) factory.createSocket(host, port);
        socket.setSoTimeout(10000);
        socket.startHandshake();
    } catch (Exception e) {
        //e.printStackTrace();
    } finally {
        if (socket != null)
            socket.close();
    }

    X509Certificate[] chain = tm.chain;
    if (chain == null)
        return;

    MessageDigest sha1 = MessageDigest.getInstance("SHA1");
    MessageDigest md5 = MessageDigest.getInstance("MD5");
    for (int i = 0; i < chain.length; i++) {
        X509Certificate cert = chain[i];
        sha1.update(cert.getEncoded());
        md5.update(cert.getEncoded());
    }

    for (int count = 0; count < chain.length; count++) {
        X509Certificate cert = chain[count];
        String alias = host + "-" + (count + 1);
        ks.setCertificateEntry(alias, cert);
        OutputStream out = new FileOutputStream("jssecacerts");
        try {
            ks.store(out, password);
        } finally {
            out.close();
        }
    }
}

From source file:org.globus.myproxy.MyProxy.java

/**
 * Bootstraps trustroot information from the MyProxy server.
 *
 * @exception MyProxyException/*  w w  w.  j av a  2  s  .  c  o  m*/
 *         If an error occurred during the operation.
 */
public void bootstrapTrust() throws MyProxyException {
    try {
        SSLContext sc = SSLContext.getInstance("SSL");
        MyTrustManager myTrustManager = new MyTrustManager();
        TrustManager[] trustAllCerts = new TrustManager[] { myTrustManager };
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        SSLSocketFactory sf = sc.getSocketFactory();
        SSLSocket socket = (SSLSocket) sf.createSocket(this.host, this.port);
        socket.setEnabledProtocols(new String[] { "SSLv3" });
        socket.startHandshake();
        socket.close();

        X509Certificate[] acceptedIssuers = myTrustManager.getAcceptedIssuers();
        if (acceptedIssuers == null) {
            throw new MyProxyException("Failed to determine MyProxy server trust roots in bootstrapTrust.");
        }
        for (int idx = 0; idx < acceptedIssuers.length; idx++) {
            File x509Dir = new File(org.globus.myproxy.MyProxy.getTrustRootPath());
            if (!x509Dir.exists()) {
                StringBuffer newSubject = new StringBuffer();
                String[] subjArr = acceptedIssuers[idx].getSubjectDN().getName().split(", ");
                for (int i = (subjArr.length - 1); i > -1; i--) {
                    newSubject.append("/");
                    newSubject.append(subjArr[i]);
                }
                String subject = newSubject.toString();

                File tmpDir = new File(getTrustRootPath() + "-" + System.currentTimeMillis());
                if (tmpDir.mkdir() == true) {
                    String hash = opensslHash(acceptedIssuers[idx]);
                    String filename = tmpDir.getPath() + tmpDir.separator + hash + ".0";

                    FileOutputStream os = new FileOutputStream(new File(filename));
                    CertificateIOUtil.writeCertificate(os, acceptedIssuers[idx]);

                    os.close();
                    if (logger.isDebugEnabled()) {
                        logger.debug("wrote trusted certificate to " + filename);
                    }

                    filename = tmpDir.getPath() + tmpDir.separator + hash + ".signing_policy";

                    os = new FileOutputStream(new File(filename));
                    Writer wr = new OutputStreamWriter(os, Charset.forName("UTF-8"));
                    wr.write("access_id_CA X509 '");
                    wr.write(subject);
                    wr.write("'\npos_rights globus CA:sign\ncond_subjects globus \"*\"\n");
                    wr.flush();
                    wr.close();
                    os.close();

                    if (logger.isDebugEnabled()) {
                        logger.debug("wrote trusted certificate policy to " + filename);
                    }

                    // success.  commit the bootstrapped directory.
                    if (tmpDir.renameTo(x509Dir) == true) {
                        if (logger.isDebugEnabled()) {
                            logger.debug("renamed " + tmpDir.getPath() + " to " + x509Dir.getPath());
                        }
                    } else {
                        throw new MyProxyException(
                                "Unable to rename " + tmpDir.getPath() + " to " + x509Dir.getPath());
                    }
                } else {
                    throw new MyProxyException("Cannot create temporary directory: " + tmpDir.getName());
                }
            }
        }
    } catch (Exception e) {
        throw new MyProxyException("MyProxy bootstrapTrust failed.", e);
    }
}