Cryptographically Secure Random Number

In a similar vein to my attempt to generate a cryptographically secure random string I also wanted to be able to create cryptographically secure random numbers.

The below function is based on the answer from Markus Olsson to the stackoverflow question here.


public static int GetRandomInteger(int minValue = 0, int maxValue = int.MaxValue)
{
	if (maxValue < minValue)
	{
		throw new ArgumentOutOfRangeException("Maximum value must be greater than minimum value");
	}
	else if (maxValue == minValue)
	{
		return 0;
	}

	Int64 diff = maxValue - minValue;

	using (RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider())
	{
		while (true)
		{
			byte[] fourBytes = new byte[4];
			crypto.GetBytes(fourBytes);

			// Convert that into an uint.
			UInt32 scale = BitConverter.ToUInt32(fourBytes, 0);

			Int64 max = (1 + (Int64)UInt32.MaxValue);
			Int64 remainder = max % diff;
			if (scale < max - remainder)
			{
				return (Int32)(minValue + (scale % diff));
			}
		}
	}
}

Leave a Reply

Your email address will not be published. Required fields are marked *