Checker Random   as of Julia version 2.6.0 (built on 6 Sep 2018)

belongs to group Basic

Identify uses of insecure random number generators


Random number con be generated with both the java.util.Random and the java.security.SecureRandom class. However, the latter generates cryptographically secure random numbers and is hence preferred. Moreover, recreating the random generator every time that a random number is needed results in a waste of resources.

This holds also in C#, where Random number con be generated with both the System.Random (cryptographically insecure) an the System.Security.Cryptography.RNGCryptoServiceProvide (cryptographically secure) class.

Action: Use java.security.SecureRandom instead of java.util.Random. Store the random generator in a field instead of a local variable.
Action: Use System.Security.Cryptography.RNGCryptoServiceProvider instead of System.Random. Store the random generator in a field instead of a local variable.

Examples


Consider the following program:

import java.util.Random;

public class Main {
  public static void main(String[] args) {
    Random r = new Random();
    int[] array = mkRandomArray(Math.abs(r.nextInt() % 1000));
    for (int i: array)
      System.out.println(i);
  }

  private static int[] mkRandomArray(int length) {
    int[] result = new int[length];
    for (int pos = 0; pos < length; pos++)
      result[pos] = new Random().nextInt();

    return result;
  }
}

This checker issues the following warnings:

Main.java:5: [Random: InsecureRandomWarning] Use of unsafe random number generator. Use java.security.SecureRandom instead
Main.java:6: [Random: SuboptimalRandomNumberWarning] Suboptimal generation of random value: the random number generator is recreated each time
Main.java:14: [Random: InsecureRandomWarning] Use of unsafe random number generator. Use java.security.SecureRandom instead
Main.java:14: [Random: SuboptimalRandomNumberWarning] Suboptimal generation of random value: the random number generator is recreated each time

since a non-cryptographically safe random number generator is used and since the random number generator is recreated each time a random number is needed.

In this example, the program could be modified as follows:

import java.security.SecureRandom;
import java.util.Random;

public class Main {
  private final static Random r = new SecureRandom();

  public static void main(String[] args) {
    int[] array = mkRandomArray(Math.abs(r.nextInt() % 1000));
    for (int i: array)
      System.out.println(i);
  }

  private static int[] mkRandomArray(int length) {
    int[] result = new int[length];
    for (int pos = 0; pos < length; pos++)
      result[pos] = r.nextInt();

    return result;
  }
}