Reputation: 821
I am building an application server in Java using the HttpServer class. I have this server functioning perfectly using plain text communication over HTTP. However, I wish to upgrade this to using SSL, using the HttpsServer class. I used this question as a basis to work from: Simple Java HTTPS server
My server class is as follows:
public Server(Options options){
SSLContext sslContext = null;
try {
server = HttpsServer.create(new InetSocketAddress(8080), 0);
sslContext = SSLContext.getInstance("TLS");
char[] password = options.getSSLPassword().toCharArray();
KeyStore ks = KeyStore.getInstance ("JKS");
FileInputStream fis = new FileInputStream (options.getSSLKeystore());
ks.load ( fis, password );
KeyManagerFactory kmf = KeyManagerFactory.getInstance ( "SunX509" );
kmf.init ( ks, password );
TrustManagerFactory tmf = TrustManagerFactory.getInstance ( "SunX509" );
tmf.init ( ks );
sslContext.init ( kmf.getKeyManagers (), tmf.getTrustManagers (), null );
} catch (Exception e) {
e.printStackTrace();
}
HttpsConfigurator httpsConfigurator = new HttpsConfigurator(sslContext) {
@Override
public void configure(HttpsParameters httpsParameters) {
SSLContext sslContext = getSSLContext();
SSLParameters defaultSSLParameters = sslContext.getDefaultSSLParameters();
httpsParameters.setSSLParameters(defaultSSLParameters);
}
};
server.createContext("/", new HttpHandler() {
@Override
public void handle(HttpExchange t) throws IOException {
HttpsExchange s = (HttpsExchange)t;
s.getSSLSession();
String response = "<html><body>Hello world.</body></html>";
t.sendResponseHeaders(200, response.length());
OutputStream os = t.getResponseBody();
os.write(response.getBytes());
os.close();
}
});
server.setExecutor(Executors.newCachedThreadPool());
System.out.println("Starting server on port " + port + "...");
server.setHttpsConfigurator(httpsConfigurator);
server.start();
System.out.println("Server started successfully!");
}
This compiles and runs fine, but then when I try to connect to through a browser on localhost:8080 I get "no data received" and on https://localhost:8080 I get "webpage is not available" There are no exceptions being thrown and it seems to run with no issues, apart from the fact that it just does nothing.
I used the keytool program to generate the keystore, however I am unfamiliar with this process so perhaps this is incorrect? But again, it accepts this as it is setting up the keystore and keyManagers etc.
Do I need to change my HttpHandler or contexts to handle an SSL exchange or something?
Upvotes: 3
Views: 2403
Reputation: 821
I have been able to get the program working with SSL with the code I provided in my question. I believe the issue I was having was because of the keystore I had generated. Using this command to generate the keystore it worked:
keytool -genkey -alias alias -keyalg RSA -keystore keystore.jks -keysize 2048
Upvotes: 4