Skip to main content

Generate a cryptographically secure random number/integer between the specified range.

        /// <summary>
        /// Generate a Random Integer (with even distribution).
        /// </summary>
        /// <param name="minimum">The minimum allowed value. Default is 0.</param>
        /// <param name="maximum">The maximum allowed value. Default is 100.</param>
        /// <returns>A random integer.</returns>
        /// <remarks>https://riptutorial.com/csharp/example/32641/cryptographically-secure-random-data</remarks>
        public static int GenerateSecureRandomInt(int minimum = 0, int maximum = 100)
        {
            var randomBytes = new byte[4];

            using (var rng = new RNGCryptoServiceProvider())
            {
                rng.GetBytes(randomBytes);
            }

            var i = Math.Abs(BitConverter.ToInt32(randomBytes, 0));

            return Convert.ToInt32(i % (maximum - minimum + 1) + minimum);
        }