Cryptography Secure TCP Sockets in Java

Well, I finally got round to testing out a basic encryption over TCP sockets.

First off, the main() entry looks very familiar and is easy to understand. I simply create the listening server (doesn’t spawn thread for simplicity), with the ability to safely shut it down.

Then I use the DataInputStream and DataOutputStream to send data back and forth. In this test case I sent a string which both the client and server will print to the console.

Once that was working, I extended the OutputStream and InputStream and override the read() and write() methods (shown in the code examples below). Notice that I manipulate the byte in two different ways, one by adding and subtracting and the other by XOR’ing (commented out but works). If these manipulations match up whilst data is being sent back and forth then there’s no errors.

Main class

The main class and entry point to the test which spawns the server and then runs a couple of tests:

package com.wlgfx.cryptotest;

public class CryptoServer {

    public static void main(String[] args) {
        WLCryptoServer server_run = new WLCryptoServer();
        Thread server = new Thread(server_run);
        server.start();
        
        System.out.println("Server thread started");
        
        new Thread(new WLCryptoClient("Hello world!")).start();
        
        try { Thread.sleep(500); } catch (InterruptedException ex) {}
        
        new Thread(new WLCryptoClient("Jump around and stomp your feet!")).start();
        
        try { Thread.sleep(500); } catch (InterruptedException ex) {}
        
        server_run.quitServer();
    }
}

Server class

The server code which take the input and output streams and creates new subclasses of the encryption layer classes and then creates the usual DataInputStream and DataOutputStream for the rest of the normal IO. This matched in the following code for the client.

package com.wlgfx.cryptotest;

import com.wlgfx.cryptotest.WLC.WLInputStream;
import com.wlgfx.cryptotest.WLC.WLOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class WLCryptoServer implements Runnable {
    
    private final int port = 1999;
    private boolean quit = false;

    @Override
    public void run() {
        try {
            ServerSocket socket =  new ServerSocket(port);
            socket.setSoTimeout(1000);
            
            while (!quit) {
                Socket client = socket.accept();
                
                WLOutputStream wlout = new WLOutputStream(client.getOutputStream());
                DataOutputStream out = new DataOutputStream(wlout);
            
                WLInputStream wlin = new WLInputStream(client.getInputStream());
                DataInputStream in = new DataInputStream(wlin);
                
                String text = in.readUTF();
                System.out.println("SERVER: " + text);
                out.writeUTF(text);
                
                client.close();
            }
        } catch (IOException ex) {
            System.out.println("SERVER: " + ex.getLocalizedMessage());
        }
    }
    
    public void quitServer() {
        quit = true;
    }
}

Client class

The client code is just the same as the server class code.

package com.wlgfx.cryptotest;

import com.wlgfx.cryptotest.WLC.WLInputStream;
import com.wlgfx.cryptotest.WLC.WLOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;

public class WLCryptoClient implements Runnable {
    
    private String text;
    private Socket socket;
    
    private final int port = 1999;
    
    public WLCryptoClient(String test) {
        text = test;
    }
    
    @Override
    public void run() {
        try {
            socket = new Socket("localhost", port);
            
            WLOutputStream wlout = new WLOutputStream(socket.getOutputStream());
            DataOutputStream out = new DataOutputStream(wlout);
            
            WLInputStream wlin = new WLInputStream(socket.getInputStream());
            DataInputStream in = new DataInputStream(wlin);
            
            out.writeUTF(text);
            text = in.readUTF();
            System.out.println("CLIENT: " + text);
            
            socket.close();
        } catch (IOException ex) {
            System.out.println("CLIENT: " + ex.getLocalizedMessage());
        }
    }
    
}

The encryption class

This is where you can see exactly how easy it is to manipulate the data being sent back and forth.  Here I am showing you two methods, XOR and add and subtract. It’s very simple, but for heavier encryption you could look further at CSPRNG, or Crypto Secure Pseudo Random Number Generator. PRNG’s are ten a penny, from simple ones to hefty things. Take your pick. The Crypto and Secure layers are the ones you really need for truly undecipherable data communication.

package com.wlgfx.cryptotest;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class WLC {

    // NB: short inner classes are static to avoid errors
    
    public static class WLInputStream extends InputStream {

        private InputStream in;

        public WLInputStream(InputStream input) {
            in = input;
        }

        @Override
        public int read() throws IOException {
            byte a = (byte) in.read();
            a--;
            return (int) a;

            //return in.read() ^ 255; // WORKS TOO
        }
    }

    public static class WLOutputStream extends OutputStream {

        private OutputStream out;

        public WLOutputStream(OutputStream output) {
            out = output;
        }

        @Override
        public void write(int b) throws IOException {
            byte a = (byte) b;
            a++;
            out.write((int) a);

            //out.write(b ^ 255); // WORKS TOO
        }
    }
}
Console output:
run:
Server thread started
SERVER: Hello world!
CLIENT: Hello world!
SERVER: Jump around and stomp your feet!
CLIENT: Jump around and stomp your feet!
SERVER: Accept timed out
BUILD SUCCESSFUL (total time: 1 second)

Until next time

😛

Posted in cryptography, encryption, Java, security, tcp, threads, Uncategorized.