Skip to content

Instantly share code, notes, and snippets.

@jtdowney
Created September 8, 2016 15:38
Show Gist options
  • Save jtdowney/097d5dedccc8939edb622c0b160fa1e8 to your computer and use it in GitHub Desktop.
Save jtdowney/097d5dedccc8939edb622c0b160fa1e8 to your computer and use it in GitHub Desktop.
package com.jtdowney;
import javax.net.ServerSocketFactory;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.security.KeyStore;
import java.security.SecureRandom;
public class Main {
public static void main(String[] args) {
try {
char[] password = "testing".toCharArray();
KeyStore keyStore = KeyStore.getInstance("JKS");
InputStream inputStream = new FileInputStream("test.keystore");
keyStore.load(inputStream, password);
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(keyStore, password);
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(keyStore);
SSLContext context = SSLContext.getInstance("TLS");
context.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), new SecureRandom());
ServerSocketFactory serverSocketFactory = context.getServerSocketFactory();
ServerSocket serverSocket = serverSocketFactory.createServerSocket(8443);
Socket clientSocket = serverSocket.accept();
InputStream clientInputStream = clientSocket.getInputStream();
InputStreamReader clientInputStreamReader = new InputStreamReader(clientInputStream);
BufferedReader clientReader = new BufferedReader(clientInputStreamReader);
while (true) {
String line = clientReader.readLine();
System.out.println(line);
if (line.isEmpty()) {
break;
}
}
OutputStream clientOutputStream = clientSocket.getOutputStream();
clientOutputStream.write("HTTP/1.1 200 OK\r\n".getBytes());
clientOutputStream.write("Content-Length: 4\r\n".getBytes());
clientOutputStream.write("Connection: close\r\n".getBytes());
clientOutputStream.write("\r\n".getBytes());
clientOutputStream.write("test".getBytes());
clientOutputStream.flush();
clientSocket.close();
serverSocket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment