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 taken from the post here.


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

	using (RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider())
	{
		uint scale = uint.MaxValue;
		while (scale == uint.MaxValue)
		{
			// Get four random bytes.
			byte[] fourBytes = new byte[4];
			crypto.GetBytes(fourBytes);

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

		// Add min to the scaled difference between max and min.
		return (int)(min + (max - min) * (scale / (double)uint.MaxValue));
	}
}

Leave a Reply

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