Java Code Examples for javax.net.ssl.SSLSocket#getOutputStream()

The following examples show how to use javax.net.ssl.SSLSocket#getOutputStream() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SSLSender.java    From fluency with Apache License 2.0 6 votes vote down vote up
@Override
protected void sendBuffers(SSLSocket sslSocket, List<ByteBuffer> buffers)
        throws IOException
{
    for (ByteBuffer buffer : buffers) {
        OutputStream outputStream = sslSocket.getOutputStream();
        if (buffer.hasArray()) {
            outputStream.write(buffer.array(), buffer.position(), buffer.remaining());
        }
        else {
            byte[] bytes = new byte[buffer.remaining()];
            buffer.get(bytes);
            outputStream.write(bytes);
        }
    }
}
 
Example 2
Source File: SSLconnection.java    From openhab1-addons with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Constructor to setup and establish a connection.
 *
 * @param host as String describing the Service Access Point location i.e. hostname.
 * @param port as String describing the Service Access Point location i.e. TCP port.
 * @throws java.net.ConnectException in case of unrecoverable communication failures.
 * @throws java.io.IOException in case of continuous communication I/O failures.
 * @throws java.net.UnknownHostException in case of continuous communication I/O failures.
 */
public SSLconnection(String host, int port) throws ConnectException, IOException, UnknownHostException {
    logger.debug("SSLconnection({},{}) called.", host, port);
    logger.info("Starting {} bridge connection.", VeluxBindingConstants.BINDING_ID);
    SSLContext ctx = null;
    try {
        ctx = SSLContext.getInstance("SSL");
        ctx.init(null, trustAllCerts, null);
    } catch (Exception e) {
        throw new IOException("create of an empty trust store failed.");
    }
    logger.trace("SSLconnection(): creating socket...");
    socket = (SSLSocket) ctx.getSocketFactory().createSocket(host, port);
    logger.trace("SSLconnection(): starting SSL handshake...");
    socket.startHandshake();
    dOut = new DataOutputStream(socket.getOutputStream());
    dIn = new DataInputStream(socket.getInputStream());
    logger.trace("SSLconnection() finished.");
}
 
Example 3
Source File: SSLSessionFinalizeTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
void doServerSide() throws Exception {
        SSLServerSocketFactory sslssf =
            (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
        SSLServerSocket sslServerSocket =
            (SSLServerSocket) sslssf.createServerSocket(serverPort);
        serverPort = sslServerSocket.getLocalPort();

        /*
         * Signal Client, we're ready for his connect.
         */
        serverReady = true;

        while (serverReady) {
            SSLSocket sslSocket = (SSLSocket) sslServerSocket.accept();
//            System.out.printf("  accept: %s%n", sslSocket);
            InputStream sslIS = sslSocket.getInputStream();
            OutputStream sslOS = sslSocket.getOutputStream();

            sslIS.read();
            sslOS.write(85);
            sslOS.flush();

            sslSocket.close();
        }
    }
 
Example 4
Source File: ExportableBlockCipher.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
void doServerSide() throws Exception {
    SSLServerSocketFactory sslssf =
        (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
    SSLServerSocket sslServerSocket =
        (SSLServerSocket) sslssf.createServerSocket(serverPort);

    serverPort = sslServerSocket.getLocalPort();

    /*
     * Signal Client, we're ready for his connect.
     */
    serverReady = true;

    SSLSocket sslSocket = (SSLSocket) sslServerSocket.accept();
    InputStream sslIS = sslSocket.getInputStream();
    OutputStream sslOS = sslSocket.getOutputStream();

    boolean interrupted = false;
    try {
        sslIS.read();
        sslOS.write('A');
        sslOS.flush();
    } catch (IOException ioe) {
        // get the expected exception
        interrupted = true;
    } finally {
        sslSocket.close();
    }

    if (!interrupted) {
        throw new SSLHandshakeException(
            "A weak cipher suite is negotiated, " +
            "TLSv1.1 must not negotiate the exportable cipher suites.");
    }
}
 
Example 5
Source File: SSLSocketTemplate.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
protected void runClientApplication(SSLSocket socket) throws Exception {
    InputStream sslIS = socket.getInputStream();
    OutputStream sslOS = socket.getOutputStream();

    sslOS.write(280);
    sslOS.flush();
    sslIS.read();
}
 
Example 6
Source File: SSLSocketTemplate.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
protected void runServerApplication(SSLSocket socket) throws Exception {
    // here comes the test logic
    InputStream sslIS = socket.getInputStream();
    OutputStream sslOS = socket.getOutputStream();

    sslIS.read();
    sslOS.write(85);
    sslOS.flush();
}
 
Example 7
Source File: ControlService.java    From deskcon-android with GNU General Public License v3.0 5 votes vote down vote up
private void receiveFiles(String[] filenames, SSLSocket socket) throws IOException {
	DataInputStream dataInFromClient = new DataInputStream(socket.getInputStream());
	BufferedReader inFromClient = new BufferedReader(new InputStreamReader(socket.getInputStream()));
	DataOutputStream outToClient = new DataOutputStream(socket.getOutputStream());
	
	File downloadfolder = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
	
	for (int i=0; i<filenames.length; i++) {
		String filename = filenames[i];

		// receive Filesize
		String ins = inFromClient.readLine();
		long filesize = Long.parseLong(ins);
		
		byte[] buffer = new byte[4096];
		int loopcnt = Math.round(filesize/4096);
		int lastbytes = (int) (filesize % 4096);

		// open File
		File newFile = new File(downloadfolder, filename);
		FileOutputStream fos = new FileOutputStream(newFile);
		
		// send ready
		outToClient.write(1);
		// send Data
		for (int j=0; j<loopcnt; j++) {
			dataInFromClient.read(buffer, 0, 4096);
			fos.write(buffer, 0, 4096);
		}
		dataInFromClient.read(buffer, 0, lastbytes);
		fos.write(buffer, 0, lastbytes);
		fos.flush();
		fos.close();						
	}
}
 
Example 8
Source File: ExportableStreamCipher.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
void doServerSide() throws Exception {
    SSLServerSocketFactory sslssf =
        (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
    SSLServerSocket sslServerSocket =
        (SSLServerSocket) sslssf.createServerSocket(serverPort);

    serverPort = sslServerSocket.getLocalPort();

    /*
     * Signal Client, we're ready for his connect.
     */
    serverReady = true;

    SSLSocket sslSocket = (SSLSocket) sslServerSocket.accept();
    InputStream sslIS = sslSocket.getInputStream();
    OutputStream sslOS = sslSocket.getOutputStream();

    boolean interrupted = false;
    try {
        sslIS.read();
        sslOS.write('A');
        sslOS.flush();
    } catch (IOException ioe) {
        // get the expected exception
        interrupted = true;
    } finally {
        sslSocket.close();
    }

    if (!interrupted) {
        throw new SSLHandshakeException(
            "A weak cipher suite is negotiated, " +
            "TLSv1.1 must not negotiate the exportable cipher suites.");
    }
}
 
Example 9
Source File: FTPClient.java    From cyberduck with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected void sslNegotiation() throws IOException {
    if(protocol.isSecure()) {
        final SSLSocket socket = (SSLSocket) sslSocketFactory.createSocket(_socket_,
                _socket_.getInetAddress().getHostAddress(), _socket_.getPort(), false);
        socket.setEnableSessionCreation(true);
        socket.setUseClientMode(true);
        socket.startHandshake();
        _socket_ = socket;
        _controlInput_ = new BufferedReader(new InputStreamReader(
                socket.getInputStream(), getControlEncoding()));
        _controlOutput_ = new BufferedWriter(new OutputStreamWriter(
                socket.getOutputStream(), getControlEncoding()));
    }
}
 
Example 10
Source File: SSLSocketTemplate.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
protected void runServerApplication(SSLSocket socket) throws Exception {
    // here comes the test logic
    InputStream sslIS = socket.getInputStream();
    OutputStream sslOS = socket.getOutputStream();

    sslIS.read();
    sslOS.write(85);
    sslOS.flush();
}
 
Example 11
Source File: SSLSocketTemplate.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
protected void runClientApplication(SSLSocket socket) throws Exception {
    InputStream sslIS = socket.getInputStream();
    OutputStream sslOS = socket.getOutputStream();

    sslOS.write(280);
    sslOS.flush();
    sslIS.read();
}
 
Example 12
Source File: ServerIdentityTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Override
protected void runServerApplication(SSLSocket socket) throws Exception {
    InputStream sslIS = socket.getInputStream();
    sslIS.read();
    BufferedWriter bw = new BufferedWriter(
            new OutputStreamWriter(socket.getOutputStream()));
    bw.write("HTTP/1.1 200 OK\r\n\r\n\r\n");
    bw.flush();
    socket.getSession().invalidate();
}
 
Example 13
Source File: GenericStreamCipher.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
void doServerSide() throws Exception {
    SSLServerSocketFactory sslssf =
        (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
    SSLServerSocket sslServerSocket =
        (SSLServerSocket) sslssf.createServerSocket(serverPort);

    // enable a stream cipher
    sslServerSocket.setEnabledCipherSuites(
        new String[] {"SSL_RSA_WITH_RC4_128_MD5"});

    serverPort = sslServerSocket.getLocalPort();

    /*
     * Signal Client, we're ready for his connect.
     */
    serverReady = true;

    SSLSocket sslSocket = (SSLSocket) sslServerSocket.accept();
    InputStream sslIS = sslSocket.getInputStream();
    OutputStream sslOS = sslSocket.getOutputStream();

    sslIS.read();
    sslOS.write('A');
    sslOS.flush();

    sslSocket.close();
}
 
Example 14
Source File: ProxyAuthTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Override
protected void runServerApplication(SSLSocket socket) throws Exception {
    String response = "Proxy authentication for tunneling succeeded ..";
    DataOutputStream out = new DataOutputStream(socket.getOutputStream());
    try {
        BufferedReader in = new BufferedReader(
                new InputStreamReader(socket.getInputStream()));

        // read the request
        readRequest(in);

        // retrieve bytecodes
        byte[] bytecodes = response.getBytes(US_ASCII);

        // send bytecodes in response (assumes HTTP/1.0 or later)
        out.writeBytes("HTTP/1.0 200 OK\r\n");
        out.writeBytes("Content-Length: " + bytecodes.length + "\r\n");
        out.writeBytes("Content-Type: text/html\r\n\r\n");
        out.write(bytecodes);
        out.flush();
    } catch (IOException e) {
        // write out error response
        out.writeBytes("HTTP/1.0 400 " + e.getMessage() + "\r\n");
        out.writeBytes("Content-Type: text/html\r\n\r\n");
        out.flush();
    }
}
 
Example 15
Source File: Connection.java    From reader with MIT License 4 votes vote down vote up
/**
 * Create an {@code SSLSocket} and perform the TLS handshake and certificate
 * validation.
 */
private void upgradeToTls(TunnelRequest tunnelRequest) throws IOException {
  Platform platform = Platform.get();

  // Make an SSL Tunnel on the first message pair of each SSL + proxy connection.
  if (requiresTunnel()) {
    makeTunnel(tunnelRequest);
  }

  // Create the wrapper over connected socket.
  socket = route.address.sslSocketFactory
      .createSocket(socket, route.address.uriHost, route.address.uriPort, true /* autoClose */);
  SSLSocket sslSocket = (SSLSocket) socket;
  if (route.modernTls) {
    platform.enableTlsExtensions(sslSocket, route.address.uriHost);
  } else {
    platform.supportTlsIntolerantServer(sslSocket);
  }

  boolean useNpn = route.modernTls && route.address.transports.contains("spdy/3");
  if (useNpn) {
    platform.setNpnProtocols(sslSocket, NPN_PROTOCOLS);
  }

  // Force handshake. This can throw!
  sslSocket.startHandshake();

  // Verify that the socket's certificates are acceptable for the target host.
  if (!route.address.hostnameVerifier.verify(route.address.uriHost, sslSocket.getSession())) {
    throw new IOException("Hostname '" + route.address.uriHost + "' was not verified");
  }

  out = sslSocket.getOutputStream();
  in = sslSocket.getInputStream();
  streamWrapper();

  byte[] selectedProtocol;
  if (useNpn && (selectedProtocol = platform.getNpnSelectedProtocol(sslSocket)) != null) {
    if (Arrays.equals(selectedProtocol, SPDY3)) {
      sslSocket.setSoTimeout(0); // SPDY timeouts are set per-stream.
      spdyConnection = new SpdyConnection.Builder(route.address.getUriHost(), true, in, out)
          .build();
      spdyConnection.sendConnectionHeader();
    } else if (!Arrays.equals(selectedProtocol, HTTP_11)) {
      throw new IOException(
          "Unexpected NPN transport " + new String(selectedProtocol, "ISO-8859-1"));
    }
  }
}
 
Example 16
Source File: FTPSClient.java    From Aria with Apache License 2.0 4 votes vote down vote up
/**
 * SSL/TLS negotiation. Acquires an SSL socket of a control
 * connection and carries out handshake processing.
 *
 * @throws IOException If server negotiation fails
 */
protected void sslNegotiation() throws IOException {
  plainSocket = _socket_;
  initSslContext();

  SSLSocketFactory ssf = context.getSocketFactory();
  String host = (_hostname_ != null) ? _hostname_ : getRemoteAddress().getHostAddress();
  int port = _socket_.getPort();
  SSLSocket socket = (SSLSocket) ssf.createSocket(_socket_, host, port, false);
  socket.setEnableSessionCreation(isCreation);
  socket.setUseClientMode(isClientMode);

  // client mode
  if (isClientMode) {
    if (tlsEndpointChecking) {
      SSLSocketUtils.enableEndpointNameVerification(socket);
    }
  } else { // server mode
    socket.setNeedClientAuth(isNeedClientAuth);
    socket.setWantClientAuth(isWantClientAuth);
  }

  if (protocols != null) {
    socket.setEnabledProtocols(protocols);
  }
  if (suites != null) {
    socket.setEnabledCipherSuites(suites);
  }
  socket.startHandshake();

  // TODO the following setup appears to duplicate that in the super class methods
  _socket_ = socket;
  _controlInput_ =
      new BufferedReader(new InputStreamReader(socket.getInputStream(), getControlEncoding()));
  _controlOutput_ =
      new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), getControlEncoding()));

  if (isClientMode) {
    if (hostnameVerifier != null && !hostnameVerifier.verify(host, socket.getSession())) {
      throw new SSLHandshakeException("Hostname doesn't match certificate");
    }
  }
}
 
Example 17
Source File: TestSsl.java    From Tomcat7.0.67 with Apache License 2.0 4 votes vote down vote up
@Test
public void testRenegotiateWorks() throws Exception {
    Tomcat tomcat = getTomcatInstance();

    Assume.assumeTrue("SSL renegotiation has to be supported for this test",
            TesterSupport.isRenegotiationSupported(getTomcatInstance()));

    File appDir = new File(getBuildDirectory(), "webapps/examples");
    // app dir is relative to server home
    tomcat.addWebapp(null, "/examples", appDir.getAbsolutePath());

    TesterSupport.initSsl(tomcat);

    tomcat.start();

    SSLContext sslCtx = SSLContext.getInstance("TLS");
    sslCtx.init(null, TesterSupport.getTrustManagers(), null);
    SSLSocketFactory socketFactory = 
            new TesterSupport.NoSSLv2SocketFactory(sslCtx.getSocketFactory());
    SSLSocket socket = (SSLSocket) socketFactory.createSocket("localhost",
            getPort());

    OutputStream os = socket.getOutputStream();

    os.write("GET /examples/servlets/servlet/HelloWorldExample HTTP/1.1\n".getBytes());
    os.flush();

    socket.startHandshake();

    try {
        os.write("Host: localhost\n\n".getBytes());
    } catch (IOException ex) {
        ex.printStackTrace();
        fail("Re-negotiation failed");
    }

    InputStream is = socket.getInputStream();
    Reader r = new InputStreamReader(is);
    BufferedReader br = new BufferedReader(r);
    String line = br.readLine();
    while (line != null) {
        // For testing System.out.println(line);
        line = br.readLine();
    }
}
 
Example 18
Source File: TestSsl.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
@Test
public void testRenegotiateWorks() throws Exception {
    Tomcat tomcat = getTomcatInstance();

    Assume.assumeTrue("SSL renegotiation has to be supported for this test",
            TesterSupport.isClientRenegotiationSupported(getTomcatInstance()));

    Context root = tomcat.addContext("", TEMP_DIR);
    Wrapper w =
        Tomcat.addServlet(root, "tester", new TesterServlet());
    w.setAsyncSupported(true);
    root.addServletMappingDecoded("/", "tester");

    TesterSupport.initSsl(tomcat);

    tomcat.start();

    SSLContext sslCtx;
    if (TesterSupport.isDefaultTLSProtocolForTesting13(tomcat.getConnector())) {
        // Force TLS 1.2 if TLS 1.3 is available as JSSE's TLS 1.3
        // implementation doesn't support Post Handshake Authentication
        // which is required for this test to pass.
        sslCtx = SSLContext.getInstance(Constants.SSL_PROTO_TLSv1_2);
    } else {
        sslCtx = SSLContext.getInstance(Constants.SSL_PROTO_TLS);
    }
    sslCtx.init(null, TesterSupport.getTrustManagers(), null);
    SSLSocketFactory socketFactory = sslCtx.getSocketFactory();
    SSLSocket socket = (SSLSocket) socketFactory.createSocket("localhost",
            getPort());

    OutputStream os = socket.getOutputStream();
    InputStream is = socket.getInputStream();
    Reader r = new InputStreamReader(is);

    doRequest(os, r);
    Assert.assertTrue("Checking no client issuer has been requested",
            TesterSupport.getLastClientAuthRequestedIssuerCount() == 0);

    TesterHandshakeListener listener = new TesterHandshakeListener();
    socket.addHandshakeCompletedListener(listener);

    socket.startHandshake();

    // One request should be sufficient
    int requestCount = 0;
    int listenerComplete = 0;
    try {
        while (requestCount < 10) {
            requestCount++;
            doRequest(os, r);
            Assert.assertTrue("Checking no client issuer has been requested",
                    TesterSupport.getLastClientAuthRequestedIssuerCount() == 0);
            if (listener.isComplete() && listenerComplete == 0) {
                listenerComplete = requestCount;
            }
        }
    } catch (AssertionError | IOException e) {
        String message = "Failed on request number " + requestCount
                + " after startHandshake(). " + e.getMessage();
        log.error(message, e);
        Assert.fail(message);
    }

    Assert.assertTrue(listener.isComplete());
    System.out.println("Renegotiation completed after " + listenerComplete + " requests");
}
 
Example 19
Source File: Connection.java    From phonegap-plugin-loading-spinner with Apache License 2.0 4 votes vote down vote up
/**
 * Create an {@code SSLSocket} and perform the TLS handshake and certificate
 * validation.
 */
private void upgradeToTls(TunnelRequest tunnelRequest) throws IOException {
  Platform platform = Platform.get();

  // Make an SSL Tunnel on the first message pair of each SSL + proxy connection.
  if (requiresTunnel()) {
    makeTunnel(tunnelRequest);
  }

  // Create the wrapper over connected socket.
  socket = route.address.sslSocketFactory
      .createSocket(socket, route.address.uriHost, route.address.uriPort, true /* autoClose */);
  SSLSocket sslSocket = (SSLSocket) socket;
  if (route.modernTls) {
    platform.enableTlsExtensions(sslSocket, route.address.uriHost);
  } else {
    platform.supportTlsIntolerantServer(sslSocket);
  }

  if (route.modernTls) {
    platform.setNpnProtocols(sslSocket, NPN_PROTOCOLS);
  }

  // Force handshake. This can throw!
  sslSocket.startHandshake();

  // Verify that the socket's certificates are acceptable for the target host.
  if (!route.address.hostnameVerifier.verify(route.address.uriHost, sslSocket.getSession())) {
    throw new IOException("Hostname '" + route.address.uriHost + "' was not verified");
  }

  out = sslSocket.getOutputStream();
  in = sslSocket.getInputStream();

  byte[] selectedProtocol;
  if (route.modernTls
      && (selectedProtocol = platform.getNpnSelectedProtocol(sslSocket)) != null) {
    if (Arrays.equals(selectedProtocol, SPDY3)) {
      sslSocket.setSoTimeout(0); // SPDY timeouts are set per-stream.
      spdyConnection = new SpdyConnection.Builder(route.address.getUriHost(), true, in, out)
          .build();
    } else if (!Arrays.equals(selectedProtocol, HTTP_11)) {
      throw new IOException(
          "Unexpected NPN transport " + new String(selectedProtocol, "ISO-8859-1"));
    }
  }
}
 
Example 20
Source File: Connection.java    From phonegapbootcampsite with MIT License 4 votes vote down vote up
/**
 * Create an {@code SSLSocket} and perform the TLS handshake and certificate
 * validation.
 */
private void upgradeToTls(TunnelRequest tunnelRequest) throws IOException {
  Platform platform = Platform.get();

  // Make an SSL Tunnel on the first message pair of each SSL + proxy connection.
  if (requiresTunnel()) {
    makeTunnel(tunnelRequest);
  }

  // Create the wrapper over connected socket.
  socket = route.address.sslSocketFactory
      .createSocket(socket, route.address.uriHost, route.address.uriPort, true /* autoClose */);
  SSLSocket sslSocket = (SSLSocket) socket;
  if (route.modernTls) {
    platform.enableTlsExtensions(sslSocket, route.address.uriHost);
  } else {
    platform.supportTlsIntolerantServer(sslSocket);
  }

  boolean useNpn = route.modernTls && route.address.transports.contains("spdy/3");
  if (useNpn) {
    platform.setNpnProtocols(sslSocket, NPN_PROTOCOLS);
  }

  // Force handshake. This can throw!
  sslSocket.startHandshake();

  // Verify that the socket's certificates are acceptable for the target host.
  if (!route.address.hostnameVerifier.verify(route.address.uriHost, sslSocket.getSession())) {
    throw new IOException("Hostname '" + route.address.uriHost + "' was not verified");
  }

  out = sslSocket.getOutputStream();
  in = sslSocket.getInputStream();
  streamWrapper();

  byte[] selectedProtocol;
  if (useNpn && (selectedProtocol = platform.getNpnSelectedProtocol(sslSocket)) != null) {
    if (Arrays.equals(selectedProtocol, SPDY3)) {
      sslSocket.setSoTimeout(0); // SPDY timeouts are set per-stream.
      spdyConnection = new SpdyConnection.Builder(route.address.getUriHost(), true, in, out)
          .build();
      spdyConnection.sendConnectionHeader();
    } else if (!Arrays.equals(selectedProtocol, HTTP_11)) {
      throw new IOException(
          "Unexpected NPN transport " + new String(selectedProtocol, "ISO-8859-1"));
    }
  }
}