Wednesday 26 November 2014

Https client and server

Post the cryptograhy session (generation of asymmetric keys), I had to use my keys to communicate between a simple https client and its corresponding server. Here's how they look like:

A simple https server:

public class MyHttpsServer {
int httpsPort = 443;
String httpsPath = "/certificate";
final EventLoopGroup parentGroup = new NioEventLoopGroup();
final EventLoopGroup childGroup = new NioEventLoopGroup();
protected final LinkedBlockingQueue<ByteBuf> incomingMsgQueue = new LinkedBlockingQueue<>();
private Channel channel;

public static void main(String[] args) throws InterruptedException {
MyHttpsServer mhs = new MyHttpsServer();
mhs.createASimpleHttpsServer();
}

public void createASimpleHttpsServer(){
try {
// setup the socket address
InetSocketAddress address = new InetSocketAddress(
InetAddress.getLocalHost(), 443);

// initialise the HTTPS server
HttpServer httpsServer = HttpsServer.create(address, 0);
SSLContext sslContext = SSLContext.getInstance("SSL");

// initialise the keystore
char[] password = "dummypassword".toCharArray();
KeyStore ks = KeyStore.getInstance("JKS");
FileInputStream fis = new FileInputStream("keysdir/my_keystore.jks");
ks.load(fis, password);

// setup the key manager factory
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(ks, password);

// setup the trust manager factory
TrustManagerFactory tmf = TrustManagerFactory
.getInstance("SunX509");
tmf.init(ks);

// setup the HTTPS context and parameters
sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
((HttpsServer) httpsServer).setHttpsConfigurator(new HttpsConfigurator(sslContext) {
public void configure(HttpsParameters params) {
try {
// initialise the SSL context
SSLContext c = SSLContext.getDefault();
SSLEngine engine = c.createSSLEngine();
params.setNeedClientAuth(false);
params.setCipherSuites(engine.getEnabledCipherSuites());
params.setProtocols(engine.getEnabledProtocols());
} catch (Exception ex) {
ex.printStackTrace();
}
}
});


httpsServer.start();
MyHttpsHandler myHttpsHandler = new MyHttpsHandler();
httpsServer.createContext(httpsPath, myHttpsHandler);
httpsServer.createContext("/key", myHttpsHandler);


System.out.println("https server is listening on " + httpsServer.getAddress());
} catch (Exception ex) {
ex.printStackTrace();
}
      }
}


Https handler (helper class):

public class MyHttpsHandler implements HttpHandler {
@Override
public void handle(HttpExchange exchange) throws IOException {
try {
if (exchange.getRequestMethod().equals("GET")) {
System.out.println("Processing the incoming GET request...." + exchange.getRequestURI().getPath());
byte[] response;
try {
response = getResponse();
exchange.sendResponseHeaders(200, response.length);
exchange.getResponseBody().write(response);
exchange.getResponseBody().close();

} catch (KeyStoreException | NoSuchAlgorithmException
| CertificateException e) {
e.printStackTrace();
} catch (UnrecoverableEntryException e) {
e.printStackTrace();
}
System.out.println("Sent response sucessfully");
} else {
System.out.println("Requested http method not supported");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}

private byte[] getResponse() throws FileNotFoundException, IOException,
KeyStoreException, NoSuchAlgorithmException, CertificateException, UnrecoverableEntryException {
File privateKeyFile = new File("keysdir/my_keystore.jks");
FileInputStream fIn = new FileInputStream(privateKeyFile);
KeyStore keyStore = KeyStore.getInstance("JKS");
keyStore.load(fIn, "dummypassword".toCharArray());
System.out.println("Successfully loaded the keystore");

Enumeration<String> aliases;
aliases = keyStore.aliases();
String alias = aliases.nextElement();
KeyStore.PrivateKeyEntry keyEnt = (KeyStore.PrivateKeyEntry) keyStore
.getEntry(
alias,
new KeyStore.PasswordProtection("dummypassword"
.toCharArray()));
PrivateKey privateKey = keyEnt.getPrivateKey();
byte[] response = privateKey.getEncoded();
return new Base64().encode(response);
}
}

No comments:

Post a Comment