using Sarand.Net.Standard.Base.Utils; using System; using System.Collections.Generic; using System.Security.Cryptography; using System.Text; namespace Sarand.Net.Standard.Base.Helpers { //======================================================================= public static class SacsRandomHelper { //------------------------------------------------------------------- // Properties. public static RandomNumberGenerator RandomNumberGenerator { get; } = RandomNumberGenerator.Create(); private static Random random; public static Random Random { get { if (random == null) random = new Random(GetInt32(Int32.MaxValue)); return random; } } public static void Fill(byte[] byteArray) { RandomNumberGenerator.Fill(byteArray); //RandomNumberGenerator.GetBytes(byteArray); } //------------------------------------------------------------------- /// /// Generates a random integer between 0 (inclusive) and a specified exclusive upper /// bound using a cryptographically strong random number generator. /// /// The exclusive upper bound of the random range. /// A random integer between 0 (inclusive) and toExclusive (exclusive). /// The toExclusive parameter is less than or equal to 0. public static int GetInt32(int toExclusive) { return RandomNumberGenerator.GetInt32(toExclusive); //return Random.Next(toExclusive); } //------------------------------------------------------------------- /// /// Generates a random integer between a specified inclusive lower bound and a specified /// exclusive upper bound using a cryptographically strong random number generator. /// /// The inclusive lower bound of the random range. /// The exclusive upper bound of the random range. /// A random integer between fromInclusive (inclusive) and toExclusive (exclusive). /// The toExclusive parameter is less than or equal to the fromInclusive parameter. public static int GetInt32(int fromInclusive, int toExclusive) { return RandomNumberGenerator.GetInt32(fromInclusive, toExclusive); //return Random.Next(fromInclusive, toExclusive); } //------------------------------------------------------------------- public static String getRandomLengthNumber(ushort maxLength=4) { String value = ""; int len = GetInt32(1, maxLength + 1); for (int i = 0; i < len; i++) value += GetInt32(0,10); if (StringUtil.IsEmpty(value)) throw new NotSupportedException("getRandomLengthNumber Generated blank value"); if (value.Length > maxLength) throw new NotSupportedException("getRandomLengthNumber Generated excess length value"); return value; } //------------------------------------------------------------------- } //======================================================================= }