##Java Random Number Generation

In the Linux operating system, there is a special device file that can be used as a random number generator or pseudo-random number generator.

/dev/random

When reading, the/dev/random device will return random bytes that are less than the total noise in the entropy pool. /Dev/random can generate highly random public keys or one-time codebooks. If the entropy pool is empty, read operations to/dev/random will be blocked until sufficient environmental noise is collected from other devices.
Of course, you can also set it to not block. When you open, you can set the parameter ONONBLOCK. However, when you read, if the entropy pool is empty, it will return -1

/dev/urandom

/A copy of dev/random is/dev/urandom (“unlocked”, non blocking random number generator [4]), which repeatedly uses data from the entropy pool to generate pseudo-random data. This means that the read operation on/dev/urandom will not block, but its output entropy may be smaller than that of/dev/random. It can be used as a pseudo-random number generator to generate lower strength passwords and is not recommended for generating high-strength long-term passwords.

##Set the method for generating random numbers

There are two ways to set a specified random number generator in JAVA

    • DAva. security. egd=file:/dev/random or - DAva. security. egd=file:/dev/urandom
  1. Modify the configuration file ‘java. security’ in jvm \ home \ jre \ lib \ security
    Parameter securerandom. source=file:/dev/urandom

Even if - DAva. security. egd=file:/dev/urandom is set, the final result is still to read file:/dev/random

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
if (egdSource.equals(URL_DEV_RANDOM) || egdSource.equals(URL_DEV_URANDOM)){ //走此分支都读/dev/random文件   
try {
instance = new NativeSeedGenerator();
if (debug != null) {
debug.println("the instance:"+instance.getClass());
debug.println("Using operating system seed generator");
}
} catch (IOException e) {
if (debug != null) {
debug.println("Failed to use operating system seed "
+ "generator: "+ e.toString());
}
}
}
else if (egdSource.length() != 0) { // 读指定的file:/dev/./urandom 或者 file:/dev/../dev/urandom文件
try {
instance = new URLSeedGenerator(egdSource);
if (debug != null) {
debug.println("Using URL seed generator reading from "
+ egdSource);
}
} catch (IOException e) {
if (debug != null)
debug.println("Failed to create seed generator with "
+ egdSource + ": " + e.toString());
}
}

因此要这样设置:-Djava.security.egd=file:/dev/./urandom