Ryepower Ryepower - 1 month ago 9
C# Question

How do I create a 2 digit random number with RNGCryptoServiceProvider class?

I am trying to get a random number but it has a certain amount of digits that I can't reduce. How can I actually get only a 2 digit random number with this secure method?

{ Console.WriteLine("{0}",GetRandom());Console.ReadLine();

}
private static int GetRandom()
{

RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
{
byte[] randomNumber = new byte[4];
rng.GetBytes(randomNumber);
int value = BitConverter.ToInt32(randomNumber,0);
return value;

Answer

Use the % known as modulo operator. It's unsual generate a range of PRNG with RNGCryptoServiceProvider but it has a smaller bias then System.Random.
Your code should look like this:

private static int GetRandom(int min, max) {
using(System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider())
        {
             byte[] randomNumber = new byte[4];
             rng.GetBytes(randomNumber);
             int value = BitConverter.ToInt32(randomNumber,0);
             return Math.Abs(value%max+min);
        }
}

I've used Math.Abs so you will get only positive number but you can remove it.