From your code I can see, you want to get a random integer number from an interval.
There is a new cryptographic random number generator included in .NET (since versions Core 3.0, Core 3.1, .NET 5, .NET 6, .NET 7 RC 1 and .NET Standard 2.1).
As jws mentioned, the formerly used class RNGCryptoServiceProvider is deprecated.
You can use this helper method. It can also easily replace the unsafe System.Random's .Next method:
/// <summary>
/// Generate a secure random number
/// </summary>
/// <param name="fromInclusive">Random number interval (min, including this number)</param>
/// <param name="toExclusive">Random number interval (max, excluding this number)</param>
/// <returns></returns>
private int RandomNumber(int fromInclusive, int toExclusive)
=> System.Security.Cryptography.RandomNumberGenerator.GetInt32(fromInclusive, toExclusive);
To simulate rolling a dice, use it like
var getNumber = RandomNumber(1, 7); // including 1, excluding 7 => 1 .. 6
If you prefer to use it "the old way" with .Next(), you can create a class like so (note that instead of a seed there are the fromInclusive and toExclusive parameters instead):
public class SecureRandom
{
private int fromInc, toExcl;
public SecureRandom(int toExclusive = 2) => Init(0, toExclusive);
public SecureRandom(int fromInclusive, int toExclusive)
=> Init(fromInclusive, toExclusive);
private void Init(int fromInclusive, int toExclusive)
{
fromInc = fromInclusive; toExcl = toExclusive;
}
public int Next() => RandomNumber(fromInc, toExcl);
public static int RandomNumber(int fromInclusive, int toExclusive)
=> System.Security.Cryptography.RandomNumberGenerator.GetInt32(fromInclusive, toExclusive);
}
Example:
// always the same interval in a loop:
var rnd = new SecureRandom(1, 7);
for (int i = 0; i < 100; i++)
{
Console.WriteLine(rnd.Next()); // roll the dice 100 times
}
// alternative usage (without creating an instance):
Console.WriteLine(SecureRandom.RandomNumber(1, 7));
Note:
This version doesn't require to get an instance from the cryptographic class any more - you just call it to get the next random number.
There's also an overload of GetInt32(...)
which takes one argument for the maximum exclusive value, which starts from the minimum value 0. If you need that, feel free to update the code and create another overloaded method for the static function RandomNumber
, like:
public static int RandomNumber(int toExclusive)
=> System.Security.Cryptography.RandomNumberGenerator.GetInt32(0, toExclusive);
}
ushort
/UInt16
). Perhaps generate either a 2-byte sequence or convert the 4-byte sequence touint
/UInt32
. I'm not sure whether the modulo affects cryptographic security in this instance. – Mummifydouble
between 0 and 1, and then multiply the result by your upper max? #2854938 – Mummify