Random class must be the first response to generate Random numbers. However, Random numbers generated by Random are called pseudo-random numbers, because when Random is used to generate Random numbers, a “seed” is needed, and the same seed must be used to generate numbers with the same sequence.
Random r1 = new Random(1);
Console.WriteLine(r1.Next(100)); / / 24
Random r2 = new Random(1);
Console.WriteLine(r2.Next(100)); / / 24
Copy the code
If no seed is provided when Random is created, the seed will be generated using the current system time.
Because the system clock has limited granularity, two Random instances that are created at very similar times (typically within 10 milliseconds) will generate the same sequence of values.
for (int i = 0; i < 10; i++)
{
Random rd = new Random();
Console.WriteLine(rd.Next(256));
}
Copy the code
Results:
43 2 2 2 2 2 2 2 2 2 2 2 2Copy the code
As you can see, there are a lot of duplicate values in this result.
Random randomness is not highly secure, and RandomNumberGenerator is a password-strength Random number generator.
var rand = System.Security.Cryptography.RandomNumberGenerator.Create();
byte[] bytes = new byte[32];
rand.GetBytes(bytes);
Copy the code
The length of the byte array determines the number of random bytes generated. Then use base64 to convert it to a string.