Example usage for javax.net.ssl SSLSocket addHandshakeCompletedListener

List of usage examples for javax.net.ssl SSLSocket addHandshakeCompletedListener

Introduction

In this page you can find the example usage for javax.net.ssl SSLSocket addHandshakeCompletedListener.

Prototype

public abstract void addHandshakeCompletedListener(HandshakeCompletedListener listener);

Source Link

Document

Registers an event listener to receive notifications that an SSL handshake has completed on this connection.

Usage

From source file:MyHandshakeListener.java

public static void main(String[] args) throws Exception {
    SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory.getDefault();
    SSLSocket socket = (SSLSocket) factory.createSocket("127.0.0.1", 8080);
    String[] suites = socket.getSupportedCipherSuites();
    socket.setEnabledCipherSuites(suites);
    socket.addHandshakeCompletedListener(new MyHandshakeListener());
    socket.startHandshake();/* www  . j av  a  2  s .c om*/
    System.out.println("Just connected to " + socket.getRemoteSocketAddress());
}

From source file:MainClass.java

public static void main(String[] args) {
    String host = args[0];// w  w w .j  a v  a 2s  .c om
    int port = Integer.parseInt(args[1]);

    try {
        System.out.println("Locating socket factory for SSL...");
        SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory.getDefault();

        System.out.println("Creating secure socket to " + host + ":" + port);
        SSLSocket socket = (SSLSocket) factory.createSocket(host, port);

        System.out.println("Enabling all available cipher suites...");
        String[] suites = socket.getSupportedCipherSuites();
        socket.setEnabledCipherSuites(suites);

        System.out.println("Registering a handshake listener...");
        socket.addHandshakeCompletedListener(new MyHandshakeListener());

        System.out.println("Starting handshaking...");
        socket.startHandshake();

        System.out.println("Just connected to " + socket.getRemoteSocketAddress());
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:org.bombusim.networking.NetworkSocketDataStream.java

public void setTLS() throws IOException {
    LimeLog.i("Socket", "Switching to secure socket layer", null);

    //TODO: check on different devices:
    // !!! ENSURE TLS enabled in account settings before test
    // 1. emulator/2.2 - SSLPeerUnverifiedException (jabber.ru, google.com) - bug in emulator v2.2
    // 2. cyanogen/2.3 - works (all hosts)
    // 3. emulator/ics - works
    // 4. Gratia/2.2 - works
    SSLSocketFactory sf =/*from  w  w  w. j a  v a  2s  . co  m*/
            //SSLCertificateSocketFactory.getDefault(20000, null);
            SSLCertificateSocketFactory.getInsecure(20000, null);

    //TODO: check on different devices:
    // 1. emulator/2.2 - works
    // 2. cyanogen/2.3 - works
    //KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); 
    //trustStore.load(null, null); 
    //SSLSocketFactory sf = new AndroidSSLSocketFactory(trustStore); 
    //sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); 

    final SSLSocket ssls = (SSLSocket) sf.createSocket(socket, host, port, true);

    ssls.addHandshakeCompletedListener(new HandshakeCompletedListener() {
        @Override
        public void handshakeCompleted(HandshakeCompletedEvent event) {
            X509Certificate[] certs;
            try {
                certs = ssls.getSession().getPeerCertificateChain();
            } catch (SSLPeerUnverifiedException e) {
                return;
            }

            StringBuilder so = new StringBuilder();

            for (X509Certificate cert : certs) {
                so.append("X509 Certificate:\n").append(" Subject:");
                appendPrincipal(so, cert.getSubjectDN());
                so.append("\n Issued by:");
                appendPrincipal(so, cert.getIssuerDN());
                so.append("\n Valid from:    ").append(DateFormat.getInstance().format(cert.getNotBefore()));
                so.append("\n Expired after: ").append(DateFormat.getInstance().format(cert.getNotAfter()));
                so.append("\n\n");
            }

            certificateInfo = so.toString();
            LimeLog.i("Socket", "Certificate chain verified", certificateInfo);
        }

        private void appendPrincipal(StringBuilder so, Principal p) {
            String name = p.getName();
            if (name == null) {
                so.append("<null>\n");
                return;
            }

            String elements[] = name.split(",");
            for (String e : elements) {
                so.append("\n   ").append(e);
            }

            so.append("\n");
        }
    });

    ssls.startHandshake();
    socket = ssls;

    istream = socket.getInputStream();
    ostream = socket.getOutputStream();

}

From source file:com.apporiented.hermesftp.cmd.impl.FtpCmdAuth.java

private SSLSocket createSslSocket() throws IOException {
    String clientHost = getCtx().getClientSocket().getInetAddress().getHostAddress();
    SSLContext sslContext = getCtx().getOptions().getSslContext();
    SSLSocketFactory factory = sslContext.getSocketFactory();
    SSLSocket sslSocket = (SSLSocket) factory.createSocket(getCtx().getClientSocket(), clientHost,
            getCtx().getOptions().getFtpPort(), true);
    sslSocket.setUseClientMode(false);/*from   www.  java2 s.c o  m*/
    sslSocket.addHandshakeCompletedListener(this);
    enableCipherSuites(sslSocket);
    log.info("Enabled cipher suites (explicit SSL): "
            + StringUtils.arrayToCommaDelimitedString(sslSocket.getEnabledCipherSuites()));
    return sslSocket;
}

From source file:org.apache.tomcat.util.net.jsse.JSSE14Support.java

public JSSE14Support(SSLSocket sock) {
    super(sock);
    sock.addHandshakeCompletedListener(listener);
}

From source file:org.beepcore.beep.profile.tls.jsse.TLSProfileJSSE.java

public void receiveMSG(MessageMSG msg) {
    Channel channel = msg.getChannel();

    InputDataStreamAdapter is = msg.getDataStream().getInputStream();

    BufferedReader reader = new BufferedReader(new InputStreamReader(is));

    String data;//from w  w w .  j a v  a2s. c  om

    try {
        try {
            data = reader.readLine();
        } catch (IOException e) {
            msg.sendERR(BEEPError.CODE_PARAMETER_ERROR, "Error reading data");
            return;
        }

        if (data.equals(READY1) == false && data.equals(READY2) == false) {
            msg.sendERR(BEEPError.CODE_PARAMETER_INVALID, "Expected READY element");
        }

        this.begin(channel);

        msg.sendRPY(new StringOutputDataStream(PROCEED2));
    } catch (BEEPException e1) {
        channel.getSession().terminate("unable to send ERR");
        return;
    }

    try {
        Socket oldSocket = ((TCPSession) channel.getSession()).getSocket();
        /** @TODO add support for serverName */
        SSLSocket newSocket = (SSLSocket) socketFactory.createSocket(oldSocket,
                oldSocket.getInetAddress().getHostName(), oldSocket.getPort(), true);

        BeepListenerHCL l = new BeepListenerHCL(channel);

        newSocket.addHandshakeCompletedListener(l);
        newSocket.setUseClientMode(false);
        newSocket.setNeedClientAuth(needClientAuth);
        newSocket.setEnabledCipherSuites(newSocket.getSupportedCipherSuites());
        if (sslProtocols != null) {
            newSocket.setEnabledProtocols(sslProtocols);
        }

        newSocket.startHandshake();
    } catch (IOException e) {
        channel.getSession().terminate("TLS error: " + e.getMessage());
        return;
    }
}

From source file:org.beepcore.beep.profile.tls.jsse.TLSProfileJSSE.java

/**
 * start a channel for the TLS profile.  Besides issuing the
 * channel start request, it also performs the initiator side
 * chores necessary to begin encrypted communication using TLS
 * over a session.  Parameters regarding the type of encryption
 * and whether or not authentication is required are specified
 * using the profile configuration passed to the <code>init</code>
 * method Upon returning, all traffic over the session will be
 * entrusted as per these parameters.<p>
 *
 * @see #init init - profile configuration
 * @param session The session to encrypt communcation for
 *
 * @return new <code>Session</code> with TLS negotiated.
 * @throws BEEPException an error occurs during the channel start
 * request or the TLS handshake (such as trying to negotiate an
 * anonymous connection with a peer that doesn't support an
 * anonymous cipher suite)./*from  w  w w  .ja  v  a2 s  .c o  m*/
 */
public TCPSession startTLS(TCPSession session) throws BEEPException {
    Channel ch = startChannel(session, uri, false, READY2, null);

    // See if we got start data back
    String data = ch.getStartData();

    if (log.isDebugEnabled()) {
        log.debug("Got start data of " + data);
    }

    // Consider the data (see if it's proceed)
    if ((data == null) || (!data.equals(PROCEED1) && !data.equals(PROCEED2))) {
        log.error("Invalid reply: " + data);
        throw new BEEPException(ERR_EXPECTED_PROCEED);
    }

    // Freeze IO and get the socket and reset it to TLS
    Socket oldSocket = session.getSocket();
    SSLSocket newSocket = null;
    TLSHandshake l = new TLSHandshake();

    // create the SSL Socket
    try {
        newSocket = (SSLSocket) socketFactory.createSocket(oldSocket, oldSocket.getInetAddress().getHostName(),
                oldSocket.getPort(), true);

        newSocket.addHandshakeCompletedListener(l);
        newSocket.setUseClientMode(true);
        newSocket.setNeedClientAuth(needClientAuth);
        newSocket.setEnabledCipherSuites(newSocket.getSupportedCipherSuites());
        if (this.sslProtocols != null) {
            newSocket.setEnabledProtocols(sslProtocols);
        }

        // set up so the handshake listeners will be called
        l.session = session;

        log.debug("Handshake starting");
        newSocket.startHandshake();
        log.debug("Handshake returned");

        synchronized (l) {
            if (!l.notifiedHandshake) {
                l.waitingForHandshake = true;

                l.wait();

                l.waitingForHandshake = false;
            }
        }
        log.debug("Handshake done waiting");
    } catch (javax.net.ssl.SSLException e) {
        log.error(e);
        throw new BEEPException(e);
    } catch (java.io.IOException e) {
        log.error(e);
        throw new BEEPException(ERR_TLS_SOCKET);
    } catch (InterruptedException e) {
        log.error(e);
        throw new BEEPException(ERR_TLS_HANDSHAKE_WAIT);
    }

    // swap it out for the new one with TLS enabled.
    if (abortSession) {
        session.close();

        throw new BEEPException(ERR_TLS_NO_AUTHENTICATION);
    } else {
        Hashtable hash = new Hashtable();

        hash.put(SessionTuningProperties.ENCRYPTION, "true");

        SessionTuningProperties tuning = new SessionTuningProperties(hash);

        return (TCPSession) reset(session, generateCredential(), l.cred, tuning, session.getProfileRegistry(),
                newSocket);
    }
}

From source file:sos.net.SOSSSLSocketFactory.java

public Socket createSocket(Socket socket, String host, int port, boolean autoClose)
        throws IOException, UnknownHostException {

    // http proxy is available
    if (proxyHost != null && proxyHost.length() > 0) {

        Socket tunnel = new Socket(proxyHost, proxyPort);

        doTunnelHandshake(tunnel, host, port);

        SSLSocket sslSocket = (SSLSocket) sslFactory.createSocket(tunnel, host, port, autoClose);

        sslSocket.addHandshakeCompletedListener(new HandshakeCompletedListener() {
            public void handshakeCompleted(HandshakeCompletedEvent event) {
                // Handshake finished!"
                done = true;// w  ww .j  a  v  a  2  s. c o  m
            }
        });
        if (!done)
            sslSocket.startHandshake();

        return sslSocket;

    } else {
        return sslFactory.createSocket(socket, host, port, autoClose);
    }
}