Secure Communication Using SSL/TLS in Java

We use Certain Steps to Secure Communication using SSL/TLS in Java are mentioned below:

Step 1: Set up the Server

  1. Create a Java project in Eclipse IDE and name it as SSLServer.
  2. Inside the SSLServer project, create one package and name it as a server.
  3. Create a Java class and name it as SSLServer.

Now replace the below code in the SSLServer class file.

Java
package server;

import javax.net.ssl.*;
import java.io.*;
import java.security.*;

public class SSLServer {
    private static final int PORT = 1234;

    public static void main(String[] args) {
        try {
            // Load keystore containing server's private key and certificate
            char[] password = "password".toCharArray();
            KeyStore keyStore = KeyStore.getInstance("JKS");

            try (FileInputStream fis = new FileInputStream("server.keystore")) {
                keyStore.load(fis, password);
            }

            // Create key manager factory
            KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
            kmf.init(keyStore, password);

            // Create SSL context
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(kmf.getKeyManagers(), null, null);

            // Create SSL server socket factory
            SSLServerSocketFactory ssf = sslContext.getServerSocketFactory();

            // Create SSL server socket
            try (SSLServerSocket serverSocket = (SSLServerSocket) ssf.createServerSocket(PORT)) {
                System.out.println("Server started. Waiting for client...");

                // Accept incoming connections
                try (SSLSocket clientSocket = (SSLSocket) serverSocket.accept()) {
                    System.out.println("Client connected.");

                    // Perform communication with client
                    try (BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                         PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true)) {

                        String message;
                        while ((message = in.readLine()) != null) {
                            System.out.println("Received from client: " + message);
                            out.println("Server received: " + message);
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Explanation of the above Program:

  1. In the above code, Load Keystore is load a keystore file contains the private key and certificate.
  2. KeyManagerFactory generate the KeyManagers with the help of keystore.
  3. Create SSLContext is initialized the KeyManagers for the server authentication.
  4. Create SSL Server Socket is used to create to the accept incoming SSL connections from the client.
  5. The server can be accept the connections from the clients and returning an SSLSocket for the each connections.
  6. After that reads the messages from the clients, and then back with the prefix and sends them back to the clients.
  7. After communication, it will be close streams and sockets to release the resources.

Note: Make sure that replace the server.keystore with path to your server keystore file.

Step 2: Set up Client

  1. Create a Java project in Eclipse IDE and name it as SSLClient.
  2. Inside the SSLClient project, create one package and name it as client.
  3. Create a Java class and name it as SSLClient.

Now replace the below code in SSLClient class file:

Java
package client;

import javax.net.ssl.*;
import java.io.*;
import java.security.*;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

public class SSLClient {
    private static final String SERVER_HOST = "localhost";
    private static final int SERVER_PORT = 1234;

    public static void main(String[] args) {
        try {
            // Create trust manager that trusts all certificates
            TrustManager[] trustManagers = new TrustManager[]{
                new X509TrustManager() {
                    @Override
                    public void checkClientTrusted(X509Certificate[] x509Certificates, String s)
                      throws CertificateException {
                    }

                    @Override
                    public void checkServerTrusted(X509Certificate[] x509Certificates, String s)
                      throws CertificateException {
                    }

                    @Override
                    public X509Certificate[] getAcceptedIssuers() {
                        return new X509Certificate[0];
                    }
                }
            };

            // Create SSL context
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, trustManagers, new SecureRandom());

            // Create SSL socket factory
            SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();

            // Create SSL socket
            try (SSLSocket socket = (SSLSocket) sslSocketFactory.createSocket(SERVER_HOST, SERVER_PORT);
                 BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                 PrintWriter out = new PrintWriter(socket.getOutputStream(), true)) {

                // Send a message to the server
                out.println("Hello, Server!");

                // Read the response from the server
                String response = in.readLine();
                System.out.println("Received from server: " + response);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Explanation of the above Program:

  1. In the above code, create a trust manager that will trusts all certificates. This is the easy implementation for the trusting any server certificate without the validation.
  2. An SSLContext is initialized with trust manager. It is represent the environment for the secure socket connections.
  3. An SSLSocketFactory is obtained from SSLContext. This factory is create SSLSockets for the communication secure.
  4. An SSLSocket is created to the connect the server at the specified port and host.
  5. Perform communication reads the from the server’s input stream and it write the output stream. It is send the message “Hello, Server!” to the server.
  6. The client reads the response from the server and it prints in the console.
  7. After the completion of the communication, the client closes the input and output streams and the socket release resources.

Step 3: Generate Keystores

  1. Open Command Prompt or Terminal.
  2. Generate a Keypair, keytool command is used to generate the keypair. This command is create the new keystore and it generates a key pair.

Write the below command in your command prompt or terminal:

keytool -genkeypair -keyalg RSA -keysize 2048 -validity 365 -alias mykey -keystore keystore.jks

After write the above code, you need to set password and give basic details such as your first & last name, organization name, state, city etc.,

Step 4: Run the Server and Client

  1. First run the SSLServer class file.
  2. After run the SSLClient class file.

The output’s as shown below in your console window:

SSLServer Output:

Output


SSLClient Output:

Output

This output is described about the client is successfully connected to the server over the SSL/TLS, sent a message and receive the response back from server. The communication between the server and the client is secure and encrypted.



How to Secure Communication Using SSL/TLS in Java?

Secure Sockets Layer (SSL) or Transport Layer Security (TLS) are cryptographic protocols designed to provide secure communication over the computer network. These protocols are establish an encrypted connection between the client and the server, make sure that the data exchanged between them remains confidential and integral.

SSL/TLS is widely used in various applications which are including web browsing, communication between emails, instant messaging, etc., It plays a crucial role in securing sensitive information like login credentials, financial transactions, personal data, and business communications transmitted through the internet. SSL/TLS provides a secure and reliable communication channel through the internet, unauthorized access and tampering.

Prerequisites:

The following are the prerequisites to secure communication using SSL/TLS in Java:

  1. Knowledge on Networking
  2. Understanding of Java Programming
  3. Basic Knowledge of Cryptographic Principles
  4. Fundamentals of Public Key Infrastructure (PKI)

Similar Reads

Secure Communication Using SSL/TLS in Java

We use Certain Steps to Secure Communication using SSL/TLS in Java are mentioned below:...