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

public abstract Socket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException;

Source Link

Document

Returns a socket layered over an existing socket connected to the named host, at the given port.

Usage

From source file:com.serphacker.serposcope.scraper.http.extensions.ScrapClientSSLConnectionFactory.java

@Override
public Socket createLayeredSocket(final Socket socket, final String target, final int port,
        final HttpContext context) throws IOException {

    SSLSocketFactory sslSocketFactory = insecure ? insecoreSSLSocketfactory : defaultSSLSocketFactory;

    final SSLSocket sslsock = (SSLSocket) sslSocketFactory.createSocket(socket, target, port, true);

    if (supportedProtocols != null) {
        sslsock.setEnabledProtocols(supportedProtocols);
    } else {//from   w w  w. ja va2  s . c om
        // If supported protocols are not explicitly set, remove all SSL protocol versions
        final String[] allProtocols = sslsock.getEnabledProtocols();
        final List<String> enabledProtocols = new ArrayList<String>(allProtocols.length);
        for (String protocol : allProtocols) {
            if (!protocol.startsWith("SSL")) {
                enabledProtocols.add(protocol);
            }
        }
        if (!enabledProtocols.isEmpty()) {
            sslsock.setEnabledProtocols(enabledProtocols.toArray(new String[enabledProtocols.size()]));
        }
    }
    if (supportedCipherSuites != null) {
        sslsock.setEnabledCipherSuites(supportedCipherSuites);
    }

    if (this.log.isDebugEnabled()) {
        this.log.debug("Enabled protocols: " + Arrays.asList(sslsock.getEnabledProtocols()));
        this.log.debug("Enabled cipher suites:" + Arrays.asList(sslsock.getEnabledCipherSuites()));
    }

    prepareSocket(sslsock);
    this.log.debug("Starting handshake");
    sslsock.startHandshake();
    verifyHostname(sslsock, target);
    return sslsock;
}

From source file:gov.miamidade.open311.utilities.SslContextedSecureProtocolSocketFactory.java

/**
 * @see SecureProtocolSocketFactory#createSocket(java.lang.String,int,java.net.InetAddress,int)
 *//*  w w  w. j a v a 2s. co m*/
public Socket createSocket(String host, int port, InetAddress clientHost, int clientPort)
        throws IOException, UnknownHostException {
    SSLSocketFactory sf = (SSLSocketFactory) getSslSocketFactory();
    SSLSocket sslSocket = (SSLSocket) sf.createSocket(host, port, clientHost, clientPort);
    verifyHostname(sslSocket);

    return sslSocket;
}

From source file:gov.miamidade.open311.utilities.SslContextedSecureProtocolSocketFactory.java

/**
 * @see SecureProtocolSocketFactory#createSocket(java.net.Socket,java.lang.String,int,boolean)
 *//*from w  w  w.ja va2 s .  c  om*/
public Socket createSocket(Socket socket, String host, int port, boolean autoClose)
        throws IOException, UnknownHostException {
    SSLSocketFactory sf = (SSLSocketFactory) getSslSocketFactory();
    SSLSocket sslSocket = (SSLSocket) sf.createSocket(socket, host, port, autoClose);
    verifyHostname(sslSocket);

    return sslSocket;
}

From source file:com.grendelscan.proxy.ssl.TunneledSSLConnection.java

public TunneledSSLConnection(Socket socket, String destinationHostname)
        throws SSLException, IOException, GeneralSecurityException {
    LOGGER.trace("Instantiating TunneledSSLConnection");
    this.destinationHostname = destinationHostname;
    this.socket = socket;
    if (socket == null) {
        IllegalArgumentException e = new IllegalArgumentException("socket cannot be null");
        LOGGER.error("Socket cannot be null", e);
        throw e;//from ww  w.  j  a v a  2  s  . c  om
    }

    if (destinationHostname == null) {
        IllegalArgumentException e = new IllegalArgumentException("destinationHostname cannot be null");
        LOGGER.error("destinationHostname cannot be null", e);
        throw e;
    }

    SSLSocketFactory sslSocketFactory = initializeSSLFactory();
    HttpParams params = MiscHttpFactory.createDefaultHttpProxyParams();

    int buffersize = HttpConnectionParams.getSocketBufferSize(params);
    sslSocket = (SSLSocket) sslSocketFactory.createSocket(socket, socket.getInetAddress().getHostAddress(),
            socket.getPort(), true);
    sslSocket.setUseClientMode(false);

    sslInputStream = sslSocket.getInputStream();
    sslTunnelInputBuffer = new SSLTunnelInputBuffer(sslInputStream, buffersize, params);

    sslOutputStream = sslSocket.getOutputStream();
    sslTunnelOutputBuffer = new SSLTunnelOutputBuffer(sslOutputStream, buffersize, params);

    // This is the real important part where we identify the buffers to the parent
    init(sslTunnelInputBuffer, sslTunnelOutputBuffer, params);
    open = true;
}

From source file:com.moilioncircle.redis.replicator.RedisSocketReplicator.java

private void connect() throws IOException {
    if (!connected.compareAndSet(false, true))
        return;//from  w  ww. ja  v  a2s.  c  o m

    socket = new Socket();
    socket.setReuseAddress(true);
    socket.setKeepAlive(true);
    socket.setTcpNoDelay(true);
    socket.setSoLinger(true, 0);
    if (configuration.getReadTimeout() > 0) {
        socket.setSoTimeout(configuration.getReadTimeout());
    }
    if (configuration.getReceiveBufferSize() > 0) {
        socket.setReceiveBufferSize(configuration.getReceiveBufferSize());
    }
    if (configuration.getSendBufferSize() > 0) {
        socket.setSendBufferSize(configuration.getSendBufferSize());
    }
    socket.connect(new InetSocketAddress(host, port), configuration.getConnectionTimeout());
    if (configuration.isSsl()) {
        SSLSocketFactory sslSocketFactory = configuration.getSslSocketFactory();
        socket = sslSocketFactory.createSocket(socket, host, port, true);

        if (configuration.getSslParameters() != null) {
            ((SSLSocket) socket).setSSLParameters(configuration.getSslParameters());
        }

        if (configuration.getHostnameVerifier() != null
                && !configuration.getHostnameVerifier().verify(host, ((SSLSocket) socket).getSession())) {
            throw new SocketException("the connection to " + host + " failed ssl/tls hostname verification.");
        }
    }
    outputStream = new RedisOutputStream(socket.getOutputStream());
    inputStream = new RedisInputStream(socket.getInputStream(), configuration.getBufferSize());
    replyParser = new ReplyParser(inputStream);
}

From source file:se.kth.infosys.lumberjack.protocol.LumberjackClient.java

public LumberjackClient(String keyStoreFile, String server, int port, int timeout) throws IOException {
    this.server = server;
    this.port = port;

    try {//from ww  w  .  j  av  a 2s . co  m
        if (keyStoreFile == null) {
            throw new IOException("Key store not configured");
        }
        if (server == null) {
            throw new IOException("Server address not configured");
        }

        keyStore = KeyStore.getInstance("JKS");
        InputStream keystoreStream = this.getClass().getClassLoader().getResourceAsStream(keyStoreFile);
        keyStore.load(keystoreStream, null);
        keystoreStream.close();

        TrustManagerFactory tmf = TrustManagerFactory.getInstance("PKIX");
        tmf.init(keyStore);

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

        SSLSocketFactory socketFactory = context.getSocketFactory();
        socket = new Socket();
        socket.connect(new InetSocketAddress(InetAddress.getByName(server), port), timeout);
        sslSocket = (SSLSocket) socketFactory.createSocket(socket, server, port, true);
        sslSocket.setUseClientMode(true);
        sslSocket.startHandshake();

        output = new DataOutputStream(new BufferedOutputStream(sslSocket.getOutputStream()));
        input = new DataInputStream(sslSocket.getInputStream());

        logger.info("Connected to {}:{}", server, port);
    } catch (IOException e) {
        throw e;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:immf.MyWiser.java

/**
 * Create a new SMTP server with this class as the listener.
 * The default port is 25. Call setPort()/setHostname() before
 * calling start()./*from  w  w  w  .  j a  v  a  2  s .  c  o m*/
 */
public MyWiser(UsernamePasswordValidator userPass, int port, MyWiserMailListener listener,
        final String tlsKeyStore, final String tlsKeyType, final String tlsKeyPasswd) {
    if (tlsKeyStore == null) {
        log.info("SMTP Server disable TLS");
        this.server = new SMTPServer(this, new EasyAuthenticationHandlerFactory(userPass));
        this.server.setHideTLS(true); // TLS?

    } else {
        // TLS
        log.info("SMTP Server enable TLS");
        this.server = new SMTPServer(this, new EasyAuthenticationHandlerFactory(userPass)) {
            public SSLSocket createSSLSocket(Socket socket) throws IOException {
                SSLSocketFactory sf = createSslSocketFactory(tlsKeyStore, tlsKeyType, tlsKeyPasswd);
                InetSocketAddress remoteAddress = (InetSocketAddress) socket.getRemoteSocketAddress();
                SSLSocket s = (SSLSocket) (sf.createSocket(socket, remoteAddress.getHostName(),
                        socket.getPort(), true));

                s.setUseClientMode(false);

                s.setEnabledCipherSuites(s.getSupportedCipherSuites());

                return s;
            }
        };
        this.server.setRequireTLS(true); // TLS
    }
    this.server.setPort(port);
    this.listener = listener;
}

From source file:com.predic8.membrane.core.transport.ssl.SSLContext.java

public Socket createSocket(InetAddress host, int port, int connectTimeout) throws IOException {
    Socket s = new Socket();
    s.connect(new InetSocketAddress(host, port), connectTimeout);
    SSLSocketFactory sslsf = sslc.getSocketFactory();
    SSLSocket ssls = (SSLSocket) sslsf.createSocket(s, host.getHostName(), port, true);
    if (protocols != null) {
        ssls.setEnabledProtocols(protocols);
    } else {/*from   ww w  . j a v a  2s  .co m*/
        String[] protocols = ssls.getEnabledProtocols();
        Set<String> set = new HashSet<String>();
        for (String protocol : protocols) {
            if (protocol.equals("SSLv3") || protocol.equals("SSLv2Hello")) {
                continue;
            }
            set.add(protocol);
        }
        ssls.setEnabledProtocols(set.toArray(new String[0]));
    }
    applyCiphers(ssls);
    return ssls;
}

From source file:com.predic8.membrane.core.transport.ssl.SSLContext.java

public Socket createSocket(InetAddress host, int port, InetAddress addr, int localPort, int connectTimeout)
        throws IOException {
    Socket s = new Socket();
    s.bind(new InetSocketAddress(addr, localPort));
    s.connect(new InetSocketAddress(host, port), connectTimeout);
    SSLSocketFactory sslsf = sslc.getSocketFactory();
    SSLSocket ssls = (SSLSocket) sslsf.createSocket(s, host.getHostName(), port, true);
    applyCiphers(ssls);/*from w w w.j  a  v  a 2s  .  co  m*/
    if (protocols != null) {
        ssls.setEnabledProtocols(protocols);
    } else {
        String[] protocols = ssls.getEnabledProtocols();
        Set<String> set = new HashSet<String>();
        for (String protocol : protocols) {
            if (protocol.equals("SSLv3") || protocol.equals("SSLv2Hello")) {
                continue;
            }
            set.add(protocol);
        }
        ssls.setEnabledProtocols(set.toArray(new String[0]));
    }
    return ssls;
}

From source file:info.fetter.logstashforwarder.protocol.LumberjackClient.java

public LumberjackClient(String keyStorePath, String server, int port, int timeout) throws IOException {
    this.server = server;
    this.port = port;

    try {/* www .  j av  a  2  s .  c  om*/
        if (keyStorePath == null) {
            throw new IOException("Key store not configured");
        }
        if (server == null) {
            throw new IOException("Server address not configured");
        }

        keyStore = KeyStore.getInstance("JKS");
        keyStore.load(new FileInputStream(keyStorePath), null);

        TrustManagerFactory tmf = TrustManagerFactory.getInstance("PKIX");
        tmf.init(keyStore);

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

        SSLSocketFactory socketFactory = context.getSocketFactory();
        socket = new Socket();
        socket.connect(new InetSocketAddress(InetAddress.getByName(server), port), timeout);
        socket.setSoTimeout(timeout);
        sslSocket = (SSLSocket) socketFactory.createSocket(socket, server, port, true);
        sslSocket.setUseClientMode(true);
        sslSocket.startHandshake();

        output = new DataOutputStream(new BufferedOutputStream(sslSocket.getOutputStream()));
        input = new DataInputStream(sslSocket.getInputStream());

        logger.info("Connected to " + server + ":" + port);
    } catch (IOException e) {
        throw e;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}