Add Some Entropy to Your JVM


Being able to generate true random numbers depends on the entropy in your system. Some claim, that this can be guaranteed by fair dice roll. Others think that replacing the OpenJDK’s java.math.Random.nextInt() method with this body will help:

public int nextInt() {
  return 14;
}

Source: http://www.redcode.nl/blog/2013/10/openjdk-and-xkcd-random-number/.

But that’s absurd. We all know that the best way to add true entropy to the JVM is by rewriting the java.lang.Integer.IntegerCache when your JVM starts up. Here’s the code:

import java.lang.reflect.Field;
import java.util.Random;

public class Entropy {
  public static void main(String[] args) 
  throws Exception {

    // Extract the IntegerCache through reflection
    Class<?> clazz = Class.forName(
      "java.lang.Integer$IntegerCache");
    Field field = clazz.getDeclaredField("cache");
    field.setAccessible(true);
    Integer[] cache = (Integer[]) field.get(clazz);

    // Rewrite the Integer cache
    for (int i = 0; i < cache.length; i++) {
      cache[i] = new Integer(
        new Random().nextInt(cache.length));
    }

    // Prove randomness
    for (int i = 0; i < 10; i++) {
      System.out.println((Integer) i);
    }
  }
}

When I last tried, the above printed

92
221
45
48
236
183
39
193
33
84

Don’t believe it? Try it on your application! By trying this on your application, you agree to the following licensing terms:

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

Tags: , , , , ,

4 responses to “Add Some Entropy to Your JVM”

  1. Peter Verhas says :

    That is not enough. You have to start your Java using the command line parameter

    java -Djava.lang.Integer.IntegerCache.high=nnnnn

    with some very high “nnnnn” number and fill those all with random numbers.

  2. Peter Verhas says :

    Or you can just change your code to

    for (Integer i = 0; i < 10; i++) {
        System.out.println((Integer) i);
    }
    

    to get more or less than 10 lines ?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 1,955 other followers

%d bloggers like this: