Exemple #1
0
        /// <summary>
        /// Uses the RDRAND instrution on Intel IvyBridge and higher CPUs
        /// to return truely random integers.
        ///
        /// CAUTION: If this code is executed
        /// on non IvyBridge CPUs, it will return null!
        /// </summary>
        /// <returns>Random unsigned integer, or 0 if no executing on compatible CPU</returns>
        public static uint GenerateUnsignedInt()
        {
            if (!RdRandLib.GeneratorAvailable())
            {
                return(0);
            }

            uint rnd = RdRandLib.Random32();

            return(rnd);
        }
Exemple #2
0
        /// <summary>
        /// Uses the RDRAND instrution on Intel IvyBridge and higher CPUs
        /// to return truely random byte arrays.
        ///
        /// CAUTION: If this code is executed
        /// on non IvyBridge CPUs, it will return null!
        /// </summary>
        /// <param name="length">Size of the byte array</param>
        /// <returns>Random byte array, or null if no executing on compatible CPU</returns>
        public static byte[] GenerateBytes(int length)
        {
            if (!RdRandLib.GeneratorAvailable())
            {
                return(null);
            }

            int numInts = length / 4 + 1;
            int idx     = 0;

            byte[] r = new byte[length];

            for (int i = 0; i < numInts; i++)
            {
                uint   rnd = RdRandLib.Random32();
                byte[] tmp = IntToBytes(rnd);

                if (idx >= length)
                {
                    return(r);
                }
                r[idx++] = tmp[0];

                if (idx >= length)
                {
                    return(r);
                }
                r[idx++] = tmp[1];

                if (idx >= length)
                {
                    return(r);
                }
                r[idx++] = tmp[2];

                if (idx >= length)
                {
                    return(r);
                }
                r[idx++] = tmp[3];
            }

            return(r);
        }
Exemple #3
0
 /// <summary>
 /// Checks for CPU compatibility with the RDRAND instruction. The RDRAND instruction
 /// is only available on Intel IvyBridge and higher CPUs.
 /// </summary>
 /// <returns>true if CPU is compatible with RDRAND</returns>
 public static bool GeneratorAvailable()
 {
     return(RdRandLib.GeneratorAvailable());
 }