Generating random bytes in Java

I recently needed to generate a bit of randomness in Java in order to produce a secret. Java comes built in with Random and SecureRandom classes which can help you do this properly but as with all things, there are multiple ways of doing things.

Two of these stood out to me.

Generate a long random number as String, convert to hex and then convert it to bytes.

You could potentially improve this method by not just converting the long number to hex string but also maybe base64 encoding it. You could potentially go further by adding additional entropy to it by filling in random bytes in random indices.

But as it stands above, the benefit of this method is that it is very quick to run. This may vary based on your random seed but I have found the above method to consistently produce byte arrays of size 14-16. This might be good enough in most cases – especially due to the fact that its fast, but in times where you might need very high amounts of entropy, the second approach might suit you.

My personal discontent with this method is that the bytes it produces will be chunked by the length of each individual hex character due to the fact that it is coming from a hex string. This, arguably is not very random. Arguably because although every individual hex characters are themselves in random order, the bytes generated off of those will have identifiable chunks representing each hex character. The second approach resolves this problem in a simpler way.

Another issue I have with this approach is that the total size is limited to the maximum value a Long can support (263-1). The size of Long data structure limits the length of hex string that gets generated which in turn limits total number of bytes produced.

The approach below resolves most of these issues.

Generate a array of random size composed of bytes and then let SecureRandom fill in those bytes.

Here, we’re creating a byte array of random size and then using secure random to fill that byte array in with random bytes. Its simple and elegant. However, as with all things, this has pros and cons of its own.

In my experiments, I have found the range of the byte array to be truly random. In a test that I ran, once it created a byte array of size 8890 while in another time, it created an array so large, I lost my patience and had to quit the process.

This poses a problem where your program could take a long time to generate your secret. Furthermore, it could potentially even go out of stack memory if the array becomes too large.

You can resolve this issue by setting a bound to the random.nextInt which is being used to determine the size of the byte array. I cannot tell you what size here is most optimal because it really depends on the capabilities of the processor you’re running on, your stack size as well as the algorithm you’re using to initialise SecureRandom. An implementation limiting the size of the byte array may look like following:

Here the size of the byte array will be between 0 and 20.

Also, please note that without the Math.abs the value for byteArraySize could be negative. If you initialise your array with a negative number for size, you will get NegativeArraySizeException.

Making executable jar using maven

I was trying something out the other day and wanted to write a really simple application. So I created a simple application backed by Maven.

Now I could run the jar file that maven built using the standard -e flag that lets java know the entry point but all that is too main stream. I wanted maven to handle that for me.

After doing some googling, I found a plugin provided by codehaus. This one allowed me to run the application through maven. As you can see below, the configuration is quite simple.

Make sure you update the value inside mainClass with fully qualified name of your class that you want to run. This class must have a public static void main method in it.

Once you are happy with the configuration, you can run your application by executing the following in your terminal

While this is great, I cannot run the jar on its own on a server somewhere. If I wanted to, I’d have to get the source code with maven and then run it using the above command. Thats sub-optimal. So I went googling again.

Finally, I found this wonderful plugin provided by our friends at Apache. This is the maven-jar-plugin. This is a standard jar plugin but one of its features is ability to specify a mainClass attribute – just like the codehaus plugin. But unlike the codehaus plugin, I can run the jar as a standalone application without needing to pass in any other flags or parameters indicating the main class.

Here’s the maven build plugin configuration to use the maven-jar-plugin.

As it is standard with maven, package up your application using:

If the build was successful, just run your jar file using standard java -jar path/to/app.jar command. In my case, I ran:

 

Enable tomcat debugging

Shutdown tomcat and make sure that it has properly shut down by monitoring the tomcat process.

Once it has completely shutdown, export the following environment variables:

Here, we’re setting the jpda address to port 8000. Note this down as you will need this port number in order to connect via your IDE or whatever debugging tool you’re using.

Options above will run tomcat as usual so if you want to debug something that happens early on in the lifecycle, you either need to be really quick about attaching your debugger or add the following JPDA option:

This will suspend the tomcat startup until you attach your debugger.

Next, start tomcat jpda using catalina script:

At this stage, you can monitor the log in catalina.out file to make sure everything goes smoothly.

Now setup your IDE to connect to tomcat at port 8000. If you are using vagrant as your VM, make sure you are port forwarding 8000 in your network settings. If not, you can always tunnel in:

Or if its a remote server, you can just use the normal ssh command:

Hope this helps!

Credits

  • Conor Restall: For suggesting JPDA_SUSPEND option.

CodeEval: Fizz Buzz (Java)

Finally managed to get some spare time in order to do this. Helped be clear my head a bit. Here’s my quick 1 minute solution to CodeEval’s fizz buzz problem in Java:

Continue reading

Blue-green deployments on AWS

Before we do this, make sure that you have a service that you want to deploy. To keep things simple, I followed the spring boot tutorial on making a restful web service. It was quick and the app worked like a charm. As usual, I went a bit extra and made my app return a stubbed list of users. You don’t have to. Make sure you have a /healthcheck endpoint and another endpoint that you can test with. In my case, I have /users which returns a list of users.

All righty then. Lets get a high level overview of what things are and how they are going to work. But before we do that, lets go through a quick real-ish life scenario.

Say you have a service that you have deployed onto AWS. Now you have a newer version of that service that you’d like to test. Since you never know if something works without actually trying it out, normally, after exhaustive testing in staging and other environments, you’d deploy that service into production to all your users. But ah ha! That one guy in your team forgot that one test case which made it blow up which means every single user of yours is now seeing error pages everywhere. This is bad so you roll it back to the previous version. Doesn’t sound too bad yet but by the time you do this, you’d have lost a couple of hours in time which would translate into actual money lost to the company which could eventually make a dent in your end of the year bonus.

Continue reading