# Use SecureRandom

# Properties

Property Value
Rule ID UseSecureRandom
First seen in jSparrow version 3.20.0
Minimum Java version 1.2
Remediation cost 5 min
Links S2245

# Description

Because the class java.util.Random relies on a pseudo-random number generator, it should not be used for security-critical applications. An attacker might be able to guess the next value generated by a pseudo-random number generator and thus access sensitive data. A more secure alternative is the class java.security.SecureRandom which relies on a cryptographically strong random number generator (RNG). This rule replaces invocations of the constructors Random() and Random(long seed) with invocations of SecureRandom. In case of a seed argument, an additional statement is generated to invoke setSeed(long seed). Sonarcloud marks this issue as "Critical" by default.

# Benefits

Prevents generating predictable pseudo-random numbers.

# Code Changes

# Using Constructor Without Any Argument

Pre

	Random random = new Random();
	byte[] bytes = new byte[20];
	random.nextBytes(bytes);

Post

	Random random = new SecureRandom();
	byte[] bytes = new byte[20];
	random.nextBytes(bytes);

# Using Constructor With Seed Argument

Pre

	Random random = new Random(System.currentTimeMillis());
	byte[] bytes = new byte[20];
	random.nextBytes(bytes);

Post

	Random random = new SecureRandom();
	random.setSeed(System.currentTimeMillis());
	byte[] bytes = new byte[20];
	random.nextBytes(bytes);

Automatic Application of This Rule

The automatic application of this rule is supported in the following jSparrow version:

# Tags

1
default
You & jSparrow
default

Hey there! May I help you? 😊