Skip to content

Instantly share code, notes, and snippets.

@ipropper
Last active October 18, 2022 05:19
Show Gist options
  • Save ipropper/7396d6f7628e34b70e92 to your computer and use it in GitHub Desktop.
Save ipropper/7396d6f7628e34b70e92 to your computer and use it in GitHub Desktop.
Simple Mutual Authentication Client with SSL Sockets (JAVA)
//CLIENT
// this method is quick and dirty, but should get the service up and running
import javax.net.SocketFactory;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import java.io.IOException;
import java.io.OutputStreamWriter;
public class Client {
public static void main (String[] args) throws IOException {
try {
// here I set my java keystore, note that these settings are GLOBAL
System.setProperty("javax.net.ssl.keyStore", "testKeyStore.keystore");
System.setProperty("javax.net.ssl.keyStorePassword", "password");
// The trust store represents the certificates I trust, If I used a certificate signed by a certificate authority(CA),
// then I would use the default java trust store. The default trust store supports most CAs. However, in this intsance, I
// am using a self signed localhost certificate, so I will supply my own trust store, identical to my keystore.
System.setProperty("javax.net.ssl.trustStore", "testKeyStore.keystore");
System.setProperty("javax.net.ssl.trustStorePassword", "password");
SocketFactory factory = SSLSocketFactory.getDefault();
String hostname = "localhost";
int port = 8000;
SSLSocket socket = (SSLSocket) factory.createSocket(hostname, port);
// this should be true by default
socket.setUseClientMode(true);
// enable all cipher suites
String[] supported = socket.getSupportedCipherSuites();
socket.setEnabledCipherSuites(supported);
try (OutputStreamWriter writer = new OutputStreamWriter(socket.getOutputStream(), "UTF-8")) {
writer.write("Hello World");
writer.flush();
}
}
catch (IOException e) {
//please throw better errors than this :)
throw new RuntimeException();
}
}
}
A quick way to test this client is to use openssl's s_server tool.
Below is an example command:
openssl s_server -Verify 1 -cert server.crt -key server.key -accept 8000
This command runs a ssl server on port 8000.The -Verify command signifies
I am looking to recieve a certificate chain from the client of depth 1.
The certificate and key that I supply are the same ones used in my clients java keystore.
In this example I only use one certificate and one key for both my server and client.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment