Java


JAVA.LIB.RAND.NEW : Single-use Random Number Generator (Java)

Summary

A random number generator is recreated each time a random number is needed.

Instead, create only one instance of a static secure random generator and use it for all random number generation.

Properties

Class Name Single-use Random Number Generator (Java)
Significance reliability
Mnemonic JAVA.LIB.RAND.NEW
Categories
CWE CWE:1176 Inefficient CPU Computation
Availability Available for Java only.
Enabling Checks for this warning class are enabled by default. To disable them, add the following WARNING_FILTER rule to the project configuration file.
WARNING_FILTER += discard class="Single-use Random Number Generator (Java)"

Example

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

public class Main {
  public static void main(String[] args) {
      Random r = new Random();                                    // Insecure Random Number Generator (Java) warning issued here
      int[] array = mkRandomArray(Math.abs(r.nextInt() % 1000));  // Single-Use Random Number Generator (Java) warning issued here
      for (int i: array)
        System.out.println(i);
      Random sr = new SecureRandom(new byte[]{1,1,1,1});          // Hardcoded Random Seed (Java) warning issued here
  }

  private static int[] mkRandomArray(int length) {
    int[] result = new int[length];
    for (int pos = 0; pos < length; pos++)
      result[pos] = new Random().nextInt();                       /* Warnings of two classes issued here:
                                                                   * - Insecure Random Number Generator (Java)
                                                                   * - Single-Use Random Number Generator (Java)
                                                                   */
    return result;
  }
}

To resolve these issues, 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);
      Random sr = new SecureRandom();
  }

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

Resolution

Use java.security.SecureRandom instead of java.util.Random. Store the random generator in a field instead of a local variable.

Relevant Configuration File Parameters

The following configuration file parameters affect checks for this warning class.