C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Caution: RNGCryptoServiceProvider has a cost: it reduces performance over the Random type.
RandomThen: We use BitConverter.ToInt32 to change those four-byte arrays into integers. This yields random integers.
BitConverterC# program that uses RNGCryptoServiceProvider
using System;
using System.Security.Cryptography;
class Program
{
static void Main()
{
using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())
{
// Buffer storage.
byte[] data = new byte[4];
// Ten iterations.
for (int i = 0; i < 10; i++)
{
// Fill buffer.
rng.GetBytes(data);
// Convert to int 32.
int value = BitConverter.ToInt32(data, 0);
Console.WriteLine(value);
}
}
}
}
Output
461315061
-1277834804
-1239389884
-1540126655
1669339804
1436197105
-473414988
-264059284
-1832694377
-1929982707
But: For important programs RNGCryptoServiceProvider is better because it is less prone to problems with its randomness.
Note: The Random type does not use the RNGCryptoServiceProvider internally. The implementations are different.
Benchmark results
Time for one random int from RNGCryptoServiceProvider: 2796.19 ns
Time for one random int from Random: 9.30 ns