Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How make SSL server socket support both http & https in java?

I'm trying to create simple web server using java sockets which should support both http & https. But i can acheive only one at a time. I need to logic which supports both http @ port 80 & https @ port 443 at same time.
This is the sample code for HTTPS Server using sslsocket. We can acheive HTTP Server using simple ServerSocket.

public class HttpsServer {
    public static void main(String[] args) {
    try {
        KeyStore ks = KeyStore.getInstance("PKCS12");
        ks.load(new FileInputStream("/opt/p12file.p12"), "p12pass".toCharArray());
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmf.init(ks, "p12pass".toCharArray());

        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(kmf.getKeyManagers(), null, null);

        SSLServerSocketFactory ssf = sc.getServerSocketFactory();
        SSLServerSocket s = (SSLServerSocket) ssf.createServerSocket(8080);

        while (true) {
            SSLSocket c = (SSLSocket) s.accept();
            BufferedWriter w = new BufferedWriter(new OutputStreamWriter(c.getOutputStream()));
            w.write("HTTP/1.0 200 OK");
            w.newLine();
            w.write("Content-Type: text/html");
            w.newLine();
            w.newLine();
            w.write("<html><body><h1>Https Server Works</h1></body></html>");
            w.newLine();
            w.flush();
            w.close();
            c.close();
        }
    }
    catch (Exception e) {
        e.printStackTrace();
    }
}

}

Can anyone help me please??

like image 457
Ranjith Avatar asked Sep 28 '22 19:09

Ranjith


1 Answers

How make SSL server socket support both http & https in java?

You can't. HTTP is plaintext, which SSLServerSocket cannot support.

I'm trying to create simple web server using java sockets which should support both http & https. But I can achieve only one at a time. I need to logic which supports both http @ port 80 & https @ port 443 at same time.

You need:

  • a plaintext ServerSocket listening at 80
  • an SSLServerSocket listening at 443
  • an accept-loop thread for each of these
  • a connection thread per accepted socket.

You will never ever get it done inside a static main() method. I suggest you read the 'Custom Networking' section of the Java Tutorial, and then the JSSE Reference Guide.

You also of course need to take a really good look at RFC 2616 HTTP 1.1. It is extremely non-trivial to implement correctly.

As suggested in comments, you should really use something off-the-shelf.

like image 196
user207421 Avatar answered Oct 06 '22 02:10

user207421