Ejemplo n.º 1
0
        /// <summary>
        /// Creates an array of bytes with a cryptographically strong random sequence of values.
        /// </summary>
        /// <param name="count">The number of bytes of random values to create.</param>
        /// <returns>
        /// An array populated with cryptographically strong random values.
        /// </returns>
        /// <exception cref="ArgumentOutOfRangeException">
        /// <paramref name="count" /> is less than zero.
        /// </exception>
        public static byte[] GetBytes(int count)
        {
            if (count < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
            }

            byte[] ret = new byte[count];
            RandomNumberGeneratorImplementation.FillSpan(ret);
            return(ret);
        }
Ejemplo n.º 2
0
        public static int GetInt32(int fromInclusive, int toExclusive)
        {
            if (fromInclusive >= toExclusive)
            {
                throw new ArgumentException(SR.Argument_InvalidRandomRange);
            }

            // The total possible range is [0, 4,294,967,295).
            // Subtract one to account for zero being an actual possibility.
            uint range = (uint)toExclusive - (uint)fromInclusive - 1;

            // If there is only one possible choice, nothing random will actually happen, so return
            // the only possibility.
            if (range == 0)
            {
                return(fromInclusive);
            }

            // Create a mask for the bits that we care about for the range. The other bits will be
            // masked away.
            uint mask = range;

            mask |= mask >> 1;
            mask |= mask >> 2;
            mask |= mask >> 4;
            mask |= mask >> 8;
            mask |= mask >> 16;

            uint        oneUint      = 0;
            Span <byte> oneUintBytes = MemoryMarshal.AsBytes(new Span <uint>(ref oneUint));
            uint        result;

            do
            {
                RandomNumberGeneratorImplementation.FillSpan(oneUintBytes);
                result = mask & oneUint;
            }while (result > range);

            return((int)result + fromInclusive);
        }
Ejemplo n.º 3
0
 public static void Fill(Span <byte> data)
 {
     RandomNumberGeneratorImplementation.FillSpan(data);
 }