Example usage for javax.net.ssl SSLServerSocketFactory getDefault

List of usage examples for javax.net.ssl SSLServerSocketFactory getDefault

Introduction

In this page you can find the example usage for javax.net.ssl SSLServerSocketFactory getDefault.

Prototype

public static ServerSocketFactory getDefault() 

Source Link

Document

Returns the default SSL server socket factory.

Usage

From source file:MainClass.java

public static void main(String[] args) {
    int port = Integer.parseInt(args[0]);

    try {/*from www .  ja va2 s . c  o  m*/
        System.out.println("Locating server socket factory for SSL...");
        SSLServerSocketFactory factory = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();

        System.out.println("Creating a server socket on port " + port);
        SSLServerSocket serverSocket = (SSLServerSocket) factory.createServerSocket(port);

        String[] suites = serverSocket.getSupportedCipherSuites();
        System.out.println("Support cipher suites are:");
        for (int i = 0; i < suites.length; i++) {
            System.out.println(suites[i]);
        }
        serverSocket.setEnabledCipherSuites(suites);

        System.out.println("Support protocols are:");
        String[] protocols = serverSocket.getSupportedProtocols();
        for (int i = 0; i < protocols.length; i++) {
            System.out.println(protocols[i]);
        }

        System.out.println("Waiting for client...");
        SSLSocket socket = (SSLSocket) serverSocket.accept();

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

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

From source file:MainClass.java

public static void main(String args[]) throws Exception {
    SSLServerSocketFactory ssf = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
    ServerSocket ss = ssf.createServerSocket(443);
    while (true) {
        Socket s = ss.accept();/*from  w  w w . ja va 2  s  .  co m*/
        PrintStream out = new PrintStream(s.getOutputStream());
        BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
        String info = null;
        String request = null;
        String refer = null;

        while ((info = in.readLine()) != null) {
            if (info.startsWith("GET")) {
                request = info;
            }
            if (info.startsWith("Referer:")) {
                refer = info;
            }
            if (info.equals(""))
                break;
        }
        if (request != null) {
            out.println("HTTP/1.0 200 OK\nMIME_version:1.0\nContent_Type:text/html");
            int sp1 = request.indexOf(' ');
            int sp2 = request.indexOf(' ', sp1 + 1);
            String filename = request.substring(sp1 + 2, sp2);
            if (refer != null) {
                sp1 = refer.indexOf(' ');
                refer = refer.substring(sp1 + 1, refer.length());
                if (!refer.endsWith("/")) {
                    refer = refer + "/";
                }
                filename = refer + filename;
            }
            URL con = new URL(filename);
            InputStream gotoin = con.openStream();
            int n = gotoin.available();
            byte buf[] = new byte[1024];
            out.println("HTTP/1.0 200 OK\nMIME_version:1.0\nContent_Type:text/html");
            out.println("Content_Length:" + n + "\n");
            while ((n = gotoin.read(buf)) >= 0) {
                out.write(buf, 0, n);
            }
            out.close();
            s.close();
            in.close();
        }
    }
}

From source file:MainClass.java

public static void main(String args[]) throws Exception {
    SSLServerSocketFactory ssf = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
    SSLServerSocket ss = (SSLServerSocket) ssf.createServerSocket(443);
    ss.setNeedClientAuth(true);// w ww.  j ava2  s .  c  o m
    while (true) {
        Socket s = ss.accept();

        SSLSession session = ((SSLSocket) s).getSession();
        Certificate[] cchain = session.getPeerCertificates();
        for (int j = 0; j < cchain.length; j++) {
            System.out.println(((X509Certificate) cchain[j]).getSubjectDN());
        }
        PrintStream out = new PrintStream(s.getOutputStream());
        BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
        String info = null;
        while ((info = in.readLine()) != null) {
            System.out.println("now got " + info);
            if (info.equals(""))
                break;
        }

        out.println("HTTP/1.0 200 OK\nMIME_version:1.0");
        out.println("Content_Type:text/html");
        String c = "<html> <head></head><body> <h1> Hi,</h1></Body></html>";
        out.println("Content_Length:" + c.length());
        out.println("");
        out.println(c);
        out.close();
        s.close();
        in.close();
    }
}

From source file:MainClass.java

public static void main(String args[]) throws Exception {
    System.setProperty("javax.net.ssl.keyStore", "lfkeystore2");
    System.setProperty("javax.net.ssl.keyStorePassword", "wshr.ut");

    SSLServerSocketFactory ssf = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
    ServerSocket ss = ssf.createServerSocket(5432);
    while (true) {
        Socket s = ss.accept();/*w w w.j a  v a 2s. c o m*/
        SSLSession session = ((SSLSocket) s).getSession();
        Certificate[] cchain2 = session.getLocalCertificates();
        for (int i = 0; i < cchain2.length; i++) {
            System.out.println(((X509Certificate) cchain2[i]).getSubjectDN());
        }
        System.out.println("Peer host is " + session.getPeerHost());
        System.out.println("Cipher is " + session.getCipherSuite());
        System.out.println("Protocol is " + session.getProtocol());
        System.out.println("ID is " + new BigInteger(session.getId()));
        System.out.println("Session created in " + session.getCreationTime());
        System.out.println("Session accessed in " + session.getLastAccessedTime());

        PrintStream out = new PrintStream(s.getOutputStream());
        out.println("Hi");
        out.close();
        s.close();
    }

}

From source file:Test.java

public static void main(String[] arstring) throws Exception {
        SSLServerSocketFactory sslServerSocketFactory = (SSLServerSocketFactory) SSLServerSocketFactory
                .getDefault();/*from  ww w.  j  a  va  2  s .c  o m*/
        SSLServerSocket sslServerSocket = (SSLServerSocket) sslServerSocketFactory.createServerSocket(9999);
        System.out.println("Waiting for a client ...");
        SSLSocket sslSocket = (SSLSocket) sslServerSocket.accept();

        SSLParameters parameters = sslSocket.getSSLParameters();
        parameters.setAlgorithmConstraints(new SimpleConstraints());

        AlgorithmConstraints constraints = parameters.getAlgorithmConstraints();
        System.out.println("Constraint: " + constraints);

        String endPoint = parameters.getEndpointIdentificationAlgorithm();
        System.out.println("End Point: " + endPoint);

        System.out.println("Local Supported Signature Algorithms");
        if (sslSocket.getSession() instanceof ExtendedSSLSession) {
            ExtendedSSLSession extendedSSLSession = (ExtendedSSLSession) sslSocket.getSession();
            String alogrithms[] = extendedSSLSession.getLocalSupportedSignatureAlgorithms();
            for (String algorithm : alogrithms) {
                System.out.println("Algortihm: " + algorithm);
            }
        }

        System.out.println("Peer Supported Signature Algorithms");
        if (sslSocket.getSession() instanceof ExtendedSSLSession) {
            String alogrithms[] = ((ExtendedSSLSession) sslSocket.getSession())
                    .getPeerSupportedSignatureAlgorithms();
            for (String algorithm : alogrithms) {
                System.out.println("Algortihm: " + algorithm);
            }
        }

        InputStream inputstream = sslSocket.getInputStream();
        InputStreamReader inputstreamreader = new InputStreamReader(inputstream);
        BufferedReader bufferedreader = new BufferedReader(inputstreamreader);

        SSLSession session = sslSocket.getHandshakeSession();
        if (session != null) {
            System.out.println("Last accessed: " + new Date(session.getLastAccessedTime()));
        }

        String string = null;
        while ((string = bufferedreader.readLine()) != null) {
            System.out.println(string);
            System.out.flush();
        }

    }

From source file:LoginClient.java

public LoginServer() throws Exception {
    SSLServerSocketFactory socketFactory = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
    serverSocket = (SSLServerSocket) socketFactory.createServerSocket(7070);

}

From source file:com.nesscomputing.syslog4j.server.impl.net.tcp.ssl.SSLTCPNetSyslogServer.java

protected ServerSocketFactory getServerSocketFactory() throws IOException {
    ServerSocketFactory serverSocketFactory = SSLServerSocketFactory.getDefault();

    return serverSocketFactory;
}

From source file:com.alecgorge.minecraft.jsonapi.NanoHTTPD.java

/**
 * Starts a HTTP server to given port.// w  w w.  j  a  v  a 2  s.  co  m
 * <p>
 * Throws an IOException if the socket is already in use
 */
public NanoHTTPD(int port, boolean ssl, InetAddress bindAddress) throws IOException {
    myTcpPort = port;

    if (ssl) {
        ServerSocketFactory ssocketFactory = SSLServerSocketFactory.getDefault();
        myServerSocket = ssocketFactory.createServerSocket(port);
    } else {
        if (bindAddress != null) {
            myServerSocket = new ServerSocket(myTcpPort, /* default value */-1, bindAddress);
        } else {
            myServerSocket = new ServerSocket(myTcpPort);
        }
    }
    myThread = new Thread(new Runnable() {
        public void run() {
            try {
                while (true)
                    new HTTPSession(myServerSocket.accept());
            } catch (IOException ioe) {
            }
        }
    });
    myThread.setDaemon(true);
    myThread.start();
}

From source file:ca.uhn.hl7v2.testpanel.model.conn.AbstractConnection.java

SocketFactory getSocketFactory() {
    return new SocketFactory() {

        @Override//  w  ww  . ja  v a  2  s .c  o m
        public Socket createTlsSocket() throws IOException {
            try {
                if (getTransport() == TransportStyleEnum.HL7_OVER_HTTP && getTlsKeystore() != null) {
                    return createHohSocketFactory().createClientSocket();
                }
            } catch (KeyStoreException e) {
                throw new IOException(e.getMessage(), e);
            }
            return SSLSocketFactory.getDefault().createSocket();
        }

        @Override
        public ServerSocket createTlsServerSocket() throws IOException {
            try {
                if (getTransport() == TransportStyleEnum.HL7_OVER_HTTP && getHohSignatureKeystore_() != null) {
                    return createHohSocketFactory().createServerSocket();
                }
            } catch (KeyStoreException e) {
                throw new IOException(e.getMessage(), e);
            }
            return SSLServerSocketFactory.getDefault().createServerSocket();
        }

        private CustomCertificateTlsSocketFactory createHohSocketFactory() throws KeyStoreException {
            KeyStore keystore = getTlsKeystore();
            String keystorePassword = getTlsKeystorePassword();
            CustomCertificateTlsSocketFactory sf = new CustomCertificateTlsSocketFactory(keystore,
                    keystorePassword);
            return sf;
        }

        @Override
        public Socket createSocket() throws IOException {
            return javax.net.SocketFactory.getDefault().createSocket();
        }

        @Override
        public ServerSocket createServerSocket() throws IOException {
            return ServerSocketFactory.getDefault().createServerSocket();
        }

        @Override
        public void configureNewAcceptedSocket(Socket theSocket) throws SocketException {
            // nothing
        }
    };
}

From source file:org.jets3t.service.FakeS3Server.java

/**
 * @param args/*w ww  . jav  a2s  .c  o m*/
 */
public static void main(String[] args) throws Exception {
    AWSCredentials fakeAwsCredentials = new AWSCredentials("fake-aws-access-key", "fake-aws-secret-key");

    int port = 443;
    ServerSocketFactory ssocketFactory = SSLServerSocketFactory.getDefault();
    ServerSocket ssocket = ssocketFactory.createServerSocket(port);
    System.out.println("Accepting connections on port 443");

    while (port == 443) {
        // Listen for connections
        Socket socket = ssocket.accept();
        System.out.println("Opened connection");

        // Create streams to securely send and receive data to the client
        InputStream in = socket.getInputStream();
        OutputStream out = socket.getOutputStream();

        byte[] buffer = new byte[1024];
        int read;

        while ((read = in.read(buffer)) != -1) {
            String receivedDataStr = new String(buffer, 0, read);
            String requestActionAndHeaders = receivedDataStr.substring(0,
                    receivedDataStr.indexOf("\r\n\r\n") + 4);

            System.out.println(requestActionAndHeaders);

            if (requestActionAndHeaders.startsWith("GET")) {
                String path = requestActionAndHeaders.substring(4, requestActionAndHeaders.indexOf(' ', 4));

                if (path.startsWith("/jets3t-")) {
                    // Return fake AWS credentials.
                    String headers = "HTTP/1.1 200 OK\r\n" + "x-amz-id-2: FakeAWSCredentials\r\n"
                            + "x-amz-request-id: FakeAWSCredentials\r\n"
                            + "Date: Thu, 24 May 2007 13:39:21 GMT\r\n" + "Cache-Control: max-age=259200\r\n"
                            + "Last-Modified: Wed, 27 Dec 2006 02:37:58 GMT\r\n"
                            + "ETag: \"fa5d6b0ea9716cf692b286b6aa187f3d\"\r\n"
                            + "Content-Type: application/octet-stream\r\n" + "Content-Length: 139\r\n"
                            + "Server: AmazonS3\r\n\r\n";

                    out.write(headers.getBytes("UTF-8"));
                    fakeAwsCredentials.save("please", out);
                }

                else if (path.equals("/")) {
                    // Return fake bucket listing.
                    String headers = "HTTP/1.1 200 OK\r\n" + "x-amz-id-2: FakeBucketListing\r\n"
                            + "x-amz-request-id: FakeBucketListing\r\n"
                            + "Date: Thu, 24 May 2007 13:39:23 GMT\r\n" + "Content-Type: application/xml\r\n"
                            + "Transfer-Encoding: chunked\r\n" + "Server: AmazonS3\r\n\r\n";

                    String bucketListing = "17b\r\n" + "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
                            + "<ListAllMyBucketsResult xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\">"
                            + "<Owner><ID>1a405254c932b52e5b5caaa88186bc431a1bacb9ece631f835daddaf0c47677c</ID>"
                            + "<DisplayName>jamesmurty</DisplayName></Owner>"
                            + "<Buckets><Bucket><Name>TestUploadBucket</Name>"
                            + "<CreationDate>2006-12-13T21:21:14.000Z</CreationDate>"
                            + "</Bucket></Buckets></ListAllMyBucketsResult>" + "\r\n0\r\n\r\n";

                    out.write(headers.getBytes("UTF-8"));
                    out.write(bucketListing.getBytes("UTF-8"));
                }

                else if (path.startsWith("/TestUploadBucket")) {
                    // Return empty bucket contents

                    String headers = "HTTP/1.1 200 OK\r\n" + "x-amz-id-2: FakeBucketContents\r\n"
                            + "x-amz-request-id: FakeBucketContents\r\n"
                            + "Date: Thu, 24 May 2007 13:39:23 GMT\r\n" + "Content-Type: application/xml\r\n"
                            + "Transfer-Encoding: chunked\r\n" + "Server: AmazonS3\r\n\r\n";

                    String bucketContents = "f2\r\n" + "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
                            + "<ListBucketResult xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\">"
                            + "<Name>TestUploadBucket</Name><Prefix></Prefix><Marker></Marker>"
                            + "<MaxKeys>1000</MaxKeys><IsTruncated>false</IsTruncated>" + "</ListBucketResult>"
                            + "\r\n0\r\n\r\n";

                    out.write(headers.getBytes("UTF-8"));
                    out.write(bucketContents.getBytes("UTF-8"));
                }

                else {
                    System.out.println("ERROR: Unrecognised GET request");
                }

            } else if (requestActionAndHeaders.startsWith("PUT")) {
                long contentLength = 0;
                String clientProvidedHash = "NONE";

                // Determine content length.
                int searchIndex = requestActionAndHeaders.indexOf("Content-Length: ")
                        + "Content-Length: ".length();
                contentLength = (new Long(requestActionAndHeaders.substring(searchIndex,
                        requestActionAndHeaders.indexOf('\r', searchIndex)))).longValue();

                // Determine content MD5 (hex encoded).
                searchIndex = requestActionAndHeaders.indexOf("Content-MD5: ") + "Content-MD5: ".length();
                if (searchIndex >= -1) {
                    clientProvidedHash = requestActionAndHeaders.substring(searchIndex,
                            requestActionAndHeaders.indexOf('\r', searchIndex));
                }

                // Read all PUT data provided by client, generating an MD5 hash as we go.
                System.out.println("Receiving " + contentLength + " bytes from client");
                MessageDigest digest = MessageDigest.getInstance("MD5");

                long putdataAlreadyRead = read - requestActionAndHeaders.length(); // read - (requestActionAndHeaders.lastIndexOf("\r\n") + 2);
                digest.update(buffer, (int) (read - putdataAlreadyRead), (int) putdataAlreadyRead);

                byte[] putdata = new byte[8192];
                int putdataRead = 0;
                while ((putdataRead = in.read(putdata)) != -1) {
                    digest.update(putdata, 0, putdataRead);
                    putdataAlreadyRead += putdataRead;

                    if (putdataAlreadyRead == contentLength) {
                        System.out.println("PUT object upload is complete");
                        break;
                    }
                }

                if (putdataAlreadyRead != contentLength) {
                    System.err.println(
                            "ERROR: Expected " + contentLength + " bytes but received " + putdataAlreadyRead);
                    continue;
                }

                String receivedDataHashAsHex = new String(Base64.encodeBase64(digest.digest()), "UTF-8");

                // Generate the headers appropriate for the PUT object.
                String headers = "HTTP/1.1 200 OK\r\n" + "x-amz-id-2: FakePUT\r\n"
                        + "x-amz-request-id: FakePUT\r\n" + "Date: Thu, 24 May 2007 15:12:30 GMT\r\n"
                        + "ETag: \"" + receivedDataHashAsHex + "\"\r\n" + "Content-Length: 0\r\n"
                        + "Server: AmazonS3\r\n\r\n";
                out.write(headers.getBytes("UTF-8"));
                out.flush();

                // Compare expected hash (supplied by client) verses actual hash (for retrieved data)
                if (!receivedDataHashAsHex.equals(clientProvidedHash)) {
                    System.err.println("ERROR: Client-side hash " + clientProvidedHash
                            + " does not match hash of received data " + receivedDataHashAsHex);
                } else {
                    System.out.println("SUCCESS: Client-side hash matches hash of received data: "
                            + receivedDataHashAsHex);
                }

            } else {
                System.out.println("ERROR: Unrecognised input");
            }
        }
        // Close the socket
        System.out.println("Closing connection");
        in.close();
        out.close();
    }
}