I have divided this task in four simple steps:
- Create a keystore.
- Create a server which is listening on port 9443.
- Create a client which will communicate to the server on port 9443.
- How to run Server and Client using SSL certificate.
Prerequisites:
JDK should be installed.
1. Create a keystore
Create a self-signed certificate using Keytool.
keytool -genkey -keyalg RSA -keystore searchyourqueries.crt -storepass password -alias searchyourqueries -keypass password -validity 3650
After executing this command you will have a certificate named “searchyourqueries.crt”.
2. Create a server which is listening on port 9443.
import javax.net.ssl.*;
import java.io.*;
public class Server
{
public static void main(String args[])
{
try
{
SSLServerSocketFactory sslserversocketfactory = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
SSLServerSocket sslserversocket = (SSLServerSocket) sslserversocketfactory.createServerSocket(9443);
SSLSocket sslsocket = (SSLSocket) sslserversocket.accept();
InputStream is = sslsocket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String str = null;
while ((str = br.readLine()) != null)
{
System.out.println(str);
System.out.flush();
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
}
Compile Server.java using: javac Server.java
3. Create a client which will communicate to the server on port 9443.
import javax.net.ssl.*;
import java.io.*;
public class Client
{
public static void main(String args[])
{
try
{
SSLSocketFactory sslsocketfactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
SSLSocket sslsocket = (SSLSocket) sslsocketfactory.createSocket(“localhost”, 9443);
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
OutputStream os = sslsocket.getOutputStream();
PrintWriter pw = new PrintWriter(os, true);
String str = null;
while ((str = br.readLine()) != null)
{
pw.write(str + ‘\n’);
pw.flush();
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
}
Complie Client.java using: javac Client.java
4. How to run Server and Client using SSL certificate.
Firstly, place the certificate which is created in Step 1 at the same location where we have our class files.
Now we need to start the Server using this certificate:
java -Djavax.net.ssl.keyStore=searchyourqueries.crt -Djavax.net.ssl.keyStorePassword=changeit Server
If we do not provide certificate information using -Djavax.net.ssl.keyStore and -Djavax.net.ssl.keyStorePassword swtiches to start the server, then it will raise an error shown below:
then start the Client using the same certificate:
java -Djavax.net.ssl.trustStore=searchyourqueries.crt -Djavax.net.ssl.trustStorePassword=changeit Client
Now your Server and Client are ready to communicate over secure channel.