Example usage for javax.net.ssl SSLSocket getOutputStream

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

Introduction

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

Prototype

public OutputStream getOutputStream() throws IOException 

Source Link

Document

Returns an output stream for this socket.

Usage

From source file:servidor.Servidor.java

public static void main(String[] arstring) {
    try {//from w w w .j  a  va 2 s.  c  o  m
        SSLServer server = new SSLServer();
        // Server needs some key material.  We'll use an OpenSSL/PKCS8 style key (possibly encrypted).
        String certificateChain = "/lib/server.crt";
        String privateKey = "/lib/server.key";
        char[] password = "clave".toCharArray();
        KeyMaterial km = new KeyMaterial(certificateChain, privateKey, password);

        server.setKeyMaterial(km);

        // These settings have to do with how we'll treat client certificates that are presented
        // to us.  If the client doesn't present any client certificate, then these are ignored.
        server.setCheckHostname(false); // default setting is "false" for SSLServer
        server.setCheckExpiry(true); // default setting is "true" for SSLServer
        server.setCheckCRL(true); // default setting is "true" for SSLServer

        // This server trusts all client certificates presented (usually people won't present
        // client certs, but if they do, we'll give them a socket at the very least).
        server.addTrustMaterial(TrustMaterial.TRUST_ALL);
        SSLServerSocket ss = (SSLServerSocket) server.createServerSocket(7443);
        SSLSocket s = (SSLSocket) ss.accept();
        PrintWriter writer = new PrintWriter(s.getOutputStream());
        BufferedReader reader = new BufferedReader(new InputStreamReader(s.getInputStream()));
        System.out.println(reader.readLine());
    } catch (Exception e) {
    }

}

From source file:clientetcp.ClienteTCP.java

public static void main(String[] args) {

    try {// w ww .  j av  a  2 s.  c  om
        SSLClient client = new SSLClient();
        SSLSocket s = (SSLSocket) client.createSocket("localhost", 7443);
        PrintWriter writer = new PrintWriter(s.getOutputStream());
        InputStream reader = s.getInputStream();
        writer.println("Hola");
    } catch (Exception exception) {

    }

}

From source file:spade.client.CommandLine.java

public static void main(String args[]) {
    // Set up context for secure connections
    try {/*ww w.  ja  v a 2  s. co m*/
        setupKeyStores();
        setupClientSSLContext();
    } catch (Exception ex) {
        System.err.println(
                CommandLine.class.getName() + " Error setting up context for secure connection. " + ex);
    }

    try {
        String host = "localhost";
        int port = Integer.parseInt(Settings.getProperty("commandline_query_port"));
        SSLSocket remoteSocket = (SSLSocket) sslSocketFactory.createSocket(host, port);

        OutputStream outStream = remoteSocket.getOutputStream();
        InputStream inStream = remoteSocket.getInputStream();
        clientInputStream = new ObjectInputStream(inStream);
        clientOutputStream = new PrintStream(outStream);
    } catch (NumberFormatException | IOException ex) {
        System.err.println(CommandLine.class.getName() + " Error connecting to SPADE! " + ex);
        System.err.println("Make sure that the CommandLine analyzer is running.");
        System.exit(-1);
    }
    try {
        System.out.println("SPADE 3.0 Query Client");
        // Set up command history and tab completion.
        ConsoleReader commandReader = new ConsoleReader();
        try {
            commandReader.getHistory().setHistoryFile(new File(historyFile));
        } catch (Exception ex) {
            System.err.println(CommandLine.class.getName() + " Command history not set up! " + ex);
        }

        while (true) {
            try {
                System.out.flush();
                System.out.print(COMMAND_PROMPT);
                String line = commandReader.readLine();
                if (StringUtils.isBlank(line)) {
                    continue;
                }
                if (line.equals(QueryCommands.QUERY_EXIT.value)) {
                    clientOutputStream.println(line);
                    break;
                } else if (line.toLowerCase().startsWith("export")) {
                    // save export path for next answer's dot file
                    parseExport(line);
                } else {
                    if (RESULT_EXPORT_PATH != null) {
                        line = "export " + line;
                    }
                    clientOutputStream.println(line);
                    String result = (String) clientInputStream.readObject();
                    if (!StringUtils.isBlank(result)) {
                        if (RESULT_EXPORT_PATH != null) {
                            FileWriter writer = new FileWriter(RESULT_EXPORT_PATH, false);
                            writer.write(result);
                            writer.flush();
                            writer.close();
                            System.out.println("Output exported to file: " + RESULT_EXPORT_PATH);
                            RESULT_EXPORT_PATH = null;
                        } else {
                            System.out.println(result);
                            System.out.println();
                        }
                    } else {
                        System.out.println("No result!");
                    }
                }
            } catch (Exception ex) {
                System.err.println(CommandLine.class.getName() + " Error talking to the client! " + ex);
            }
        }
    } catch (IOException ex) {
        System.err.println(CommandLine.class.getName() + " Error in CommandLine Client! " + ex);
    }
}

From source file:Test.java

  public static void main(String[] args) throws Exception {

  SSLSocketFactory sslSocketFactory = (SSLSocketFactory) SSLSocketFactory
      .getDefault();/*ww w.  j a  v  a 2  s. c om*/
  SSLSocket sslSocket = (SSLSocket) sslSocketFactory.createSocket(
      "localhost", 9999);

  InputStreamReader inputStreamReader = new InputStreamReader(System.in);
  BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

  OutputStream outputStream = sslSocket.getOutputStream();
  OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream);
  BufferedWriter bufferedwriter = new BufferedWriter(outputStreamWriter);

  String line = null;
  while ((line = bufferedReader.readLine()) != null) {
    bufferedwriter.write(line + '\n');
    bufferedwriter.flush();
  }
}

From source file:MainClass.java

public static void main(String[] args) throws Exception {
    SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory.getDefault();

    String hostName = "hostName";
    String fileName = "fileName";

    SSLSocket sslsock = (SSLSocket) factory.createSocket(hostName, 443);

    SSLSession session = sslsock.getSession();
    X509Certificate cert;// ww w.ja va 2  s. c  o  m
    try {
        cert = (X509Certificate) session.getPeerCertificates()[0];
    } catch (SSLPeerUnverifiedException e) {
        System.err.println(session.getPeerHost() + " did not present a valid certificate.");
        return;
    }

    System.out.println(session.getPeerHost() + " has presented a certificate belonging to:");
    Principal p = cert.getSubjectDN();
    System.out.println("\t[" + p.getName() + "]");
    System.out.println("The certificate bears the valid signature of:");
    System.out.println("\t[" + cert.getIssuerDN().getName() + "]");

    System.out.print("Do you trust this certificate (y/n)? ");
    System.out.flush();
    BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
    if (Character.toLowerCase(console.readLine().charAt(0)) != 'y')
        return;

    PrintWriter out = new PrintWriter(sslsock.getOutputStream());

    out.print("GET " + fileName + " HTTP/1.0\r\n\r\n");
    out.flush();

    BufferedReader in = new BufferedReader(new InputStreamReader(sslsock.getInputStream()));
    String line;
    while ((line = in.readLine()) != null)
        System.out.println(line);

    sslsock.close();
}

From source file:com.tc.simple.apn.quicktests.Test.java

/**
 * @param args//  w  ww .  j  a v  a 2  s . co m
 */

public static void main(String[] args) {
    SSLSocket socket = null;

    try {
        String host = "gateway.sandbox.push.apple.com";
        int port = 2195;

        String token = "de7f197546e41a76684f8e2d89f397ed165298d7772f4bd9b0f39c674b185b0f";
        System.out.println(token.toCharArray().length);

        //String token = "8cebc7c08f79fa62f0994eb4298387ff930857ff8d14a50de431559cf476b223";

        KeyStore keyStore = KeyStore.getInstance("PKCS12");

        keyStore.load(Test.class.getResourceAsStream("egram-dev-apn.p12"), "xxxxxxxxx".toCharArray());
        KeyManagerFactory keyMgrFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyMgrFactory.init(keyStore, "xxxxxxxxx".toCharArray());

        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(keyMgrFactory.getKeyManagers(), null, null);
        SSLSocketFactory socketFactory = sslContext.getSocketFactory();

        socket = (SSLSocket) socketFactory.createSocket(host, port);
        String[] cipherSuites = socket.getSupportedCipherSuites();
        socket.setEnabledCipherSuites(cipherSuites);
        socket.startHandshake();

        char[] t = token.toCharArray();
        byte[] b = Hex.decodeHex(t);

        OutputStream outputstream = socket.getOutputStream();

        String payload = "{\"aps\":{\"alert\":\"yabadabadooo\"}}";

        int expiry = (int) ((System.currentTimeMillis() / 1000L) + 7200);

        ByteArrayOutputStream bout = new ByteArrayOutputStream();

        DataOutputStream dos = new DataOutputStream(bout);

        //command
        dos.writeByte(1);

        //id
        dos.writeInt(900);

        //expiry
        dos.writeInt(expiry);

        //token length.
        dos.writeShort(b.length);

        //token
        dos.write(b);

        //payload length
        dos.writeShort(payload.length());

        //payload.
        dos.write(payload.getBytes());

        byte[] byteMe = bout.toByteArray();

        socket.getOutputStream().write(byteMe);

        socket.setSoTimeout(900);
        InputStream in = socket.getInputStream();

        System.out.println(APNErrors.getError(in.read()));

        in.close();

        outputstream.close();

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            socket.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

From source file:Messenger.TorLib.java

public static void postToURL(String hostname, int port, String postKey, String data) throws IOException {
    Socket socket = TorSocket(hostname, port);
    SSLSocketFactory sslSf = (SSLSocketFactory) SSLSocketFactory.getDefault();
    SSLSocket sslSocket = (SSLSocket) sslSf.createSocket(socket, null, socket.getPort(), false);
    sslSocket.setUseClientMode(true);/* ww  w . j  a v  a2s.  c  o m*/
    sslSocket.startHandshake();
    String path = "/" + postKey;
    BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(sslSocket.getOutputStream(), "UTF8"));
    wr.write("POST " + path + " HTTP/1.0\r\n");
    wr.write("Content-Length: " + data.length() + "\r\n");
    wr.write("Content-Type: application/x-www-form-urlencoded\r\n");
    wr.write("\r\n");

    wr.write(data);
    wr.flush();

    BufferedReader rd = new BufferedReader(new InputStreamReader(sslSocket.getInputStream()));
    String line;
    while ((line = rd.readLine()) != null) {
        System.out.println(line);
    }
    wr.close();
    rd.close();
    sslSocket.close();
}

From source file:Messenger.TorLib.java

/**
 * This method makes a http GET request for the specified resource to the specified hostname.
 * It uses the SOCKS proxy to a connection over Tor.
 * The DNS lookup is also done over Tor.
 * This method only uses port 443 for SSL.
 *
 * @param hostname hostname for target server.
 * @param port port to connect to.//from   w ww .  j  a v a 2  s. com
 * @param resource resource to lookup with GET request.
 * @return returns a JSON object.
 * @throws IOException
 * @throws JSONException
 */
public static JSONObject getJSON(String hostname, int port, String resource)
        throws IOException, JSONException, HttpException {
    //Create a SSL socket using Tor
    Socket socket = TorSocket(hostname, port);
    SSLSocketFactory sslSf = (SSLSocketFactory) SSLSocketFactory.getDefault();
    SSLSocket sslSocket = (SSLSocket) sslSf.createSocket(socket, null, socket.getPort(), false);
    sslSocket.setUseClientMode(true);
    sslSocket.startHandshake();
    openSockets.add(sslSocket);

    //Create the HTTP GET request and push it over the outputstream
    BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(sslSocket.getOutputStream(), "UTF8"));
    wr.write("GET /" + resource + " HTTP/1.0\r\n");
    wr.write("Host: " + hostname + "\r\n");
    wr.write("\r\n");
    wr.flush();

    //Listen for a response on the inputstream
    BufferedReader br = new BufferedReader(new InputStreamReader(sslSocket.getInputStream()));
    String t;
    boolean start = false;
    String output = "";
    while ((t = br.readLine()) != null) {
        if (t.equals("")) {
            start = true;
        }
        if (start) {
            output = output + t;
        }
    }
    br.close();
    wr.close();
    sslSocket.close();
    System.out.println(output);
    openSockets.remove(sslSocket);
    return new JSONObject(output);
}

From source file:LoginClient.java

public LoginClient() {
    try {/*from   w ww.ja va2  s .  c  om*/
        SSLSocketFactory socketFactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
        SSLSocket socket = (SSLSocket) socketFactory.createSocket("localhost", 7070);
        PrintWriter output = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
        String userName = "MyName";
        output.println(userName);
        String password = "MyPass";
        output.println(password);
        output.flush();
        BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        String response = input.readLine();
        System.out.println(response);

        output.close();
        input.close();
        socket.close();
    } catch (IOException ioException) {
        ioException.printStackTrace();
    } finally {
        System.exit(0);
    }
}

From source file:LoginClient.java

private void runServer() {
    while (true) {
        try {//from   w  ww. j  a  v  a  2s.  com
            System.err.println("Waiting for connection...");
            SSLSocket socket = (SSLSocket) serverSocket.accept();
            BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            PrintWriter output = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
            String userName = input.readLine();
            String password = input.readLine();

            if (userName.equals(CORRECT_USER_NAME) && password.equals(CORRECT_PASSWORD)) {
                output.println("Welcome, " + userName);
            } else {
                output.println("Login Failed.");
            }
            output.close();
            input.close();
            socket.close();

        } catch (IOException ioException) {
            ioException.printStackTrace();
        }
    }
}