Elsewhere there are things that we all miss, yet it takes just one to notice...

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

😛

Tonight I’ve sussed out the thread pooling in Java. I wanted a way of being able to queue up threads to be run, but I also wanted to allow the execution of so many threads at a time in this pool. I’ve heard about these thread pools but as of yet, not used them. I need something like this for my own project for both the server and the client.

package threadpooltest;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;

public class ThreadPoolTest {

    public static void main(String[] args) {
        ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(5);
        
        for (int i = 0; i <= 8; i++)
        {
            WorkerTest task = new WorkerTest("Task " + i);
            System.out.println("A new task has been added : " + task.getName());
            executor.execute(task);
        }
        
        System.out.println("Main thread sleeping");
        try { Thread.sleep(8000); } 
        catch (InterruptedException ex) {}
        System.out.println("Finished sleeping");
        
        for (int i = 0; i <= 10; i++)
        {
            WorkerTest task = new WorkerTest("Task " + (i + 5));
            System.out.println("A new task has been added : " + task.getName());
            executor.execute(task);
        }
        
        // THIS DOESN'T WORK
        //System.out.println("WAITING FOR TASKS TO FINISH");
        //try { executor.awaitTermination(1, TimeUnit.DAYS); } 
        //catch (InterruptedException ex) {}
        //System.out.println("FINISHED");
        
        executor.shutdown();
    }
    
}

No proper code snippet plugin yet! Grrr!

Anyway, the above code creates the thread pool which will run a max of 5 threads and queue the rest up. Just what I wanted.

package threadpooltest;

import java.util.concurrent.TimeUnit;

public class WorkerTest implements Runnable {

    private String name;
    
    public WorkerTest(String name) {
        this.name = name;
    }
    
    public String getName() {
        return name;
    }
    
    @Override
    public void run() {
        try
        {
            Long duration = (long) (Math.random() * 5);
            System.out.println("Start Task: " + name);
            TimeUnit.SECONDS.sleep(duration);
            System.out.println("Finished Task: " + name);
        }
        catch (InterruptedException e) {}
    }
}

The above is the example thread I was testing this with.

All I need now is to do the same with C++, but I’ve already found a header only project on github that does just that.

More to come…

EDIT:

I’ve also noted that the above works on Android too.

At the moment, I’m not holding my breath to see it this works with GWT.

Not really an update…

Another week done and a few wins at work. I’ve been writing code to display graphics for statistical data. ie. Sales targets and stuff. Most of the awkward stuff was having to accommodate for different resolutions, portrait and landscape modes and also having to calculate the font metrics. All done though although I do need to make a few adjustments to get the advanced settings to work properly.

My personal project has gone on hold until this weekend (tomorrow), because  two hours on an evening is not enough time to get stuck in to it. I need thinking time more than I need coding time. And then I need debugging time.

I have noticed though over this past year, I can write a shed load of code, a good few hundred to over a thousand lines of code, before I can finally test it out and it works. Well, saying it works, it’s easier to fix the bugs when it finally comes to testing.

This weekend I want to test communication over the internet using a crypto secure pseudo random number generator, or CSPRNG. Basically the client and server socket connections will be able to communicate without the transmitted data being viewed by any outsiders. The technique is quite simple, it’s the implementation of it and how it is handled that needs to be secured. Other systems use private keys, hashes, passwords, etc. A long list of security protocols. I kind of like the two stage authentication. Because this will be running through four pieces of software, I’ve devised a two way security system. Only access is allowed from the outside from my PC (if that is my work station) or my phone. And then, if this takes off, text message stage too. It boils down to a ‘real’ MAC address and the ‘fake’ MAC address. TCP communications can hopefully solve this by authenticating a number of things.

Anyway… I’m tired. Beers are knocking me out, and as usual, not my brain cell. So good night…

PS. Any up-scaling in the future I’ve made a few mental notes.

A day spent programming

Yep, a day of blitzing code.

There’s a total of four pieces of software I’m writing for this project. The server. The media manager. The device manager. And the device player. All four of them are now well on the way to being tested out soon enough.

So far the server works flawlessly with the media manager which can run on any OS, ie Linux, Windows or Mac.

The player is for embedded Linux only and also has some in built security layers.

The device manager runs on Android which makes it so much easier when setting up the devices.

The next step is to get the device player software to handle communication with the server and retrieve its playlist and it’s all ready for the big demo.

Once the demo setup has been produced I can move on to adding all the security layers in which will include encrypted communications over the internet.

Blender progress

I’ve got the mother-in-law down for a few days so programming after work is out because I can’t ‘zone’ with all the conversations going on.

This hasn’t stopped me from working with Blender to increase my skills with it though.

I can now easily import 3D models and animate them. Slamming text and jiggling them around is very easy too. All in all, another good demonstration video produced in a little over an hour. Fast moving 3D animated text and models with a video textured background. I’ve impressed myself this time. No stopping me now.

The server software and the Android app development will continue within the next two days when I can ‘zone’ again. There’s not much left to do on the media management software. Then there’s the device management through an android app. I’m also looking into SSL and other cryptography methods for secure communication all round.

Still improving with Blender

As well as the programming blitz I had over this weekend to get my server up and running which still has a bit of work left to do, I’ve also done a few bits with Blender.

In blender, I am still having an issue with the sun light shadow not being consistent. This ended up with me asking some of my contacts on social media about it.

One suggestion worked which was using an orthographic camera instead of the perspective. It was short lived though as all my animations would end up being flat.

In the same response, the friend also suggested angling the camera and using a bevelled edge on the text. Now this technique did work much better but the sun light is still causing the lighting shadow problem.

Now what I’ve done is to angle the camera and set the sun light up at the angle that works best for now. The text creation in blender get extruded and a light bevel which gives the rendered image an almost decent look to it. It will work for most things, so that will have to do for the time being. I may dig further into blender.stackexchange to see if there are any solutions to this, and if not then I will ask a question.

For text produced using GIMP, I’ve also figured out how to cast shadows through the transparency of the image. This will come in handy for a lot of things.

When using the animations, i.e. moving objects around the scene, the default movement settings for most things were fine. But I wanted to ‘slam’ text on the screen. The default settings would slow down, or ‘ease in’ the movement. Without even googling it, I figured out how to change the ‘ease in’ and ‘ease out’ settings. I can now ‘slam’ objects onto the screen. A simple, but effective effect.

Server media management

I’m glad to announce that my media server manager is very almost completed. The files upload to their respective categories and the Java application handles the media library perfectly.

It took a bit of learning Swing in Java but that wasn’t hard at all.

There’s a couple of things to do in the media manager before it is completed. Remove media and categories from the server. And add descriptions to the media files. And that’s it.

The next step is the Android application to manage devices so that I can set them up on the go without the need to get back to my PC.

Unknown devices (those that are ready to be set up) will be stored in the root directory of the media server. The Android application will then assign it a category and a playlist.

All looking good now.

(I’m having a bit of difficulty with WordPress Code Snippets so I’ve been unable to add any snippets recently)

Love this laptop

I’ve an old Dell Precision 4500, i7 @ 2Ghz with an nVidia Quadro 1800M. I got it cheap off eBay and upgraded it. RAM went from 4Gb to 8Gb, replaced the 320Gb HD with a 960Gb SSD and added a 1Tb HD in the place of the DVD drive. I use it for 95% of home use now.

Oh, and I added USB 3.0 to one of the PCI slots.

The eSata port has come in extremely handy on many occasions too. I don’t know what it would be like having to swap drives in the laptop all the time whilst I was upgrading other laptops.

Simply put, it is fast…

Tonight I tested myself against the clock with creating a demonstration video in Blender. In the background my laptop was moving a load of files from the SSD to the 1Tb HD. I wanted to get everything done within an hour. No programming tonight.

First 5 minutes was thinking of an idea, then it took about 10 minutes to collect artwork together and create the project folder with the assets.

The demonstration, with a video texture, lighting and shadow, was all done within an hour. I was happy tonight.

The test of my laptop didn’t end there.

I decided to create a new project with another demonstration idea, while Blender was rendering the project as a video file. *big grin* nothing slowed down even though the CPU was being obliterated.

Yup, I like this laptop.

Running Linux and Windows 10, but all my work gets done in Linux.

Only a minor update

After work today I was zapped, but I got the file structure tested and confirmed on the server side for the initial testing. Everything is using Linux so it is easy to set up the testing grounds. I’m trying to make the device installation as quick as possible with minimal fussing about.

Oh and I also fixed a bug with the ‘~’ (home) location in java. Using ‘user.home’ gives me the home directory (actually on Windows too I found out but not tested, no need).

Eventually all of this will be in C++ so I’m 0% stressing at the moment. The servers will need to be C++ because of the JVM overhead.

I also fixed my PC in Linux which was not connecting to many websites. I had set up the fixed IP for testing without setting the routers gateway correctly. Chrome seems to mask this by loading up some websites but the rest it couldn’t find. The fix was done by assigning the fixed IP on the routers side. Eventually a VPS will cause me a few headaches.

I think tomorrow I will get back down to using Blender because that is the main source for this project. Royalty free 3D models/animations I want to test out.

Posts navigation

1 2 3 5 6 7 8 9 10 11 12 13
Scroll to top