Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Types of randomness

Tags:

java

java-8

Java's stock Random libraries include Random and SecureRandom (and I see ThreadLocalRandom as well). Are there any others? When would I use each? Sometimes I use SecureRandom just to feel better about my simple numbers. It turns out that SecureRandom actually lets you pick your generator. How and when should I use this?

Finally, Java 8 provides SecureRandom.getInstanceStrong(). I am not sure what this is, but it's much slower than any of the previous. How and when should I use SecureRandom.getInstanceStrong()? Also, is it slow because the noise source is running out?

like image 829
Simon Kuang Avatar asked Dec 20 '22 15:12

Simon Kuang


1 Answers

Random is predictable, you just need a small sequence of the generated numbers and you can walk both forward and backwards through the sequence. See Inverse function of Java's Random function for an example of reversing the sequence.

SecureRandom is not.

ThreadLocalRandom is an attempt to fix the fact that Random is not thread safe.

Other forms of random are possible with different features - you will have to study the maths of random numbers to to be able to balance between the ones you mentioned and any other algorithm.

SecureRandom getInstanceStrong() (note the Strong) seems to be an even stronger random sequence that is especially resilient to exposing long sequences.

Randomness

Randomness can be measured statistically - I won't go into detail here, there are loads of resources out there that explain how this can be done.

It is comparatively easy to think up an algorithm that generate a statistically random sequence. However, if you only attempt statistical randomness and expect it to be a good source for encrypting your data you are mistaken. You might as well use:

private static int lastRandom = 0;

public static int nextRandom() {
  return ++lastRandom;
}

The sequence generated will probably not pass the statistical tests for randomness but it would be about as predictable.

Predictability

This is a completely different mathematical problem far beyond a simple StackOverflow answer. If you want to generate a random number sequence that is not predictable at all you may as well use a Geiger counter or similar unpredictable hardware source. Have a look here for some interesting discussion.

Security

The problem is that a good encryption sequence must find the balance between making it difficult to reproduce while not making it impossible to reproduce. An impossible to reproduce sequence of random numbers is useless for encryption because you would never be able to reproduce the same sequence to decrypt.

Achieving difficult to reproduce without becoming impossible is the dream of cryptography. Again there are many resources but Wikipedia is, as usual, an excellent start.

like image 116
OldCurmudgeon Avatar answered Jan 09 '23 15:01

OldCurmudgeon