Ejemplo n.º 1
0
        public static System.Guid GetGuid(IRandom rand)
        {
            byte[] buffer = new byte[16];
            rand.NextBytes(buffer);

            return new System.Guid(buffer);
        }
Ejemplo n.º 2
0
        public static System.Byte[] GetBinary(IRandom rand, int minLength, int maxLength)
        {
            int length = rand.Next(minLength, maxLength);
            byte[] result = new byte[length];
            rand.NextBytes(result);

            return result;
        }
Ejemplo n.º 3
0
        public static string GenerateToken(IRandom random, int tokenSizeInBytes)
        {
            if (tokenSizeInBytes <= 0 || 1024 < tokenSizeInBytes)
            {
                throw new ArgumentOutOfRangeException(nameof(tokenSizeInBytes));
            }

            Span <byte> tokenBytes = stackalloc byte[tokenSizeInBytes];

            random.NextBytes(tokenBytes);

            return(Convert.ToBase64String(tokenBytes));
        }
Ejemplo n.º 4
0
        public static System.Double GetDouble(	IRandom rand, 
												System.Double min = System.Double.MinValue, 
												System.Double max = System.Double.MaxValue)
        {
            byte[] buffer = new byte[8];
            rand.NextBytes(buffer);

            System.Double result = System.BitConverter.ToDouble(buffer, 0);

            if(result < min)
                return min;
            else if(result >= max)
                return max - 1;
            else
                return result;
        }
Ejemplo n.º 5
0
        public void NextDouble_ShouldReturnRandomDouble(
            byte a, byte b, byte c, byte d, double expected)
        {
            IRandom rand = A.Fake <Random>();

            A.CallTo(() => rand.NextBytes(A <byte[]> ._))
            .Invokes((byte[] buf) => {
                buf[0] = a;
                buf[1] = b;
                buf[2] = c;
                buf[3] = d;
            });

            var r = rand.NextDouble();

            r.Should().Be(expected);
        }
Ejemplo n.º 6
0
        public void Next_WithLowerUpperBound_ShouldReturnRandomInt(
            byte a, byte b, byte c, byte d, int expected)
        {
            IRandom rand = A.Fake <Random>();

            A.CallTo(() => rand.NextBytes(A <byte[]> ._))
            .Invokes((byte[] buf) => {
                buf[0] = a;
                buf[1] = b;
                buf[2] = c;
                buf[3] = d;
            });

            var r = rand.Next(42, 69);

            r.Should().Be(expected);
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Generates a UUID version 4, i.e., a random <see cref="Guid"/>.
        /// Please refer to <a href="https://tools.ietf.org/html/rfc4122#section-4.4">RFC 4122</a>.
        /// </summary>
        /// <param name="random"> <see cref="IRandom"/> to generate
        /// a random <see cref="Guid"/>.</param>
        /// <returns> Generated random <see cref="Guid"/>.
        /// </returns>
        /// <seealso cref="IRandom"/>
        public static Guid GenerateRandomGuid(this IRandom random)
        {
            var b = new byte[16];

            random.NextBytes(b);

            // Set the four most significant bits (bits 12 through 15) of the time_hi_and_version
            // field to the 4-bit version number. V4 is 0 1 0 0.
            // This modifies b[7] not b[6] because time_hi_and_version is stored as short type
            // in .NET like below:
            // (short) ((int) b[7] << 8 | (int) b[6])
            b[7] = (byte)((b[7] & 0x0f) | 0x40);

            // Set the two most significant bits (bits 7 and 6) of the clock_seq_hi_and_reserved
            // to one and zero, respectively.
            b[8] = (byte)((b[8] & 0x3f) | 0x80);

            return(new Guid(b));
        }
Ejemplo n.º 8
0
 /// <summary>
 ///  32ビット符号付き整数値を生成します。
 /// </summary>
 /// <param name="random">疑似乱数生成器です。</param>
 /// <returns>結果の分からない値を返します。</returns>
 public static int NextSInt32(this IRandom random)
 {
     return(BitConverter.ToInt32(random.NextBytes(4), 0));
 }
Ejemplo n.º 9
0
 /// <summary>
 ///  16ビット符号付き整数値を生成します。
 /// </summary>
 /// <param name="random">疑似乱数生成器です。</param>
 /// <returns>結果の分からない値を返します。</returns>
 public static short NextSInt16(this IRandom random)
 {
     return(BitConverter.ToInt16(random.NextBytes(2), 0));
 }
Ejemplo n.º 10
0
 /// <summary>
 ///  8ビット符号付き整数値を生成します。
 /// </summary>
 /// <param name="random">疑似乱数生成器です。</param>
 /// <returns>結果の分からない値を返します。</returns>
 public static sbyte NextSInt8(this IRandom random)
 {
     return(unchecked ((sbyte)(random.NextBytes(1)[0])));
 }
Ejemplo n.º 11
0
 /// <summary>
 ///  8ビット符号無し整数値を生成します。
 /// </summary>
 /// <param name="random">疑似乱数生成器です。</param>
 /// <returns>結果の分からない値を返します。</returns>
 public static byte NextUInt8(this IRandom random)
 {
     return(random.NextBytes(1)[0]);
 }
Ejemplo n.º 12
0
 public void Next_Bytes()
 {
     _random.NextBytes(new byte[32]);
 }
        public BigInteger(
            int bitLength,
            int certainty,
            IRandom random)
        {
            if (bitLength < 2)
                throw new ArithmeticException("bitLength < 2");

            this.SignValue = 1;
            this.nBitLength = bitLength;

            if (bitLength == 2)
            {
                this.Magnitude = random.Next(2) == 0
                                     ? Two.Magnitude
                                     : Three.Magnitude;
                return;
            }

            int nBytes = GetByteLength(bitLength);
            var b = new byte[nBytes];

            int xBits = BitsPerByte*nBytes - bitLength;
            byte mask = rndMask[xBits];

            for (;;)
            {
                random.NextBytes(b);

                // strip off any excess bits in the MSB
                b[0] &= mask;

                // ensure the leading bit is 1 (to meet the strength requirement)
                b[0] |= (byte) (1 << (7 - xBits));

                // ensure the trailing bit is 1 (i.e. must be odd)
                b[nBytes - 1] |= 1;

                this.Magnitude = MakeMagnitude(b, 0, b.Length);
                this.nBits = -1;
                this.mQuote = -1L;

                if (certainty < 1)
                    break;

                if (CheckProbablePrime(certainty, random))
                    break;

                if (bitLength > 32)
                {
                    for (int rep = 0; rep < 10000; ++rep)
                    {
                        int n = 33 + random.Next(bitLength - 2);
                        this.Magnitude[this.Magnitude.Length - (n >> 5)] ^= (1 << (n & 31));
                        this.Magnitude[this.Magnitude.Length - 1] ^= ((random.Next() + 1) << 1);
                        this.mQuote = -1L;

                        if (CheckProbablePrime(certainty, random))
                            return;
                    }
                }
            }
        }
        public BigInteger(int sizeInBits, IRandom random)
        {
            if (sizeInBits < 0)
                throw new ArgumentException("sizeInBits must be non-negative");

            this.nBits = -1;
            this.nBitLength = -1;

            if (sizeInBits == 0)
            {
                //				this.sign = 0;
                this.Magnitude = ZeroMagnitude;
                return;
            }

            int nBytes = GetByteLength(sizeInBits);
            var b = new byte[nBytes];
            random.NextBytes(b);

            // strip off any excess bits in the MSB
            b[0] &= rndMask[BitsPerByte*nBytes - sizeInBits];

            this.Magnitude = MakeMagnitude(b, 0, b.Length);
            this.SignValue = this.Magnitude.Length < 1 ? 0 : 1;
        }
Ejemplo n.º 15
0
        /// <summary>
        ///     Perform WebSocket client upgrade
        /// </summary>
        /// <param name="response">WebSocket upgrade HTTP response</param>
        /// <param name="id">WebSocket client Id</param>
        /// <returns>'true' if the WebSocket was successfully upgrade, 'false' if the WebSocket was not upgrade</returns>
        public Boolean PerformClientUpgrade(HttpNetworkResponse response, Guid id)
        {
            if (response.Status != 101)
            {
                return(false);
            }

            Boolean error      = false;
            Boolean accept     = false;
            Boolean connection = false;
            Boolean upgrade    = false;

            // Validate WebSocket handshake headers
            for (Int32 i = 0; i < response.Headers; ++i)
            {
                Tuple <String, String> header = response.Header(i);
                String key   = header.Item1;
                String value = header.Item2;

                if (key == "Connection")
                {
                    if (value != "Upgrade")
                    {
                        error = true;
                        _wsHandler.OnWsError("Invalid WebSocket handshaked response: 'Connection' header value must be 'Upgrade'");
                        break;
                    }

                    connection = true;
                }
                else if (key == "Upgrade")
                {
                    if (value != "websocket")
                    {
                        error = true;
                        _wsHandler.OnWsError("Invalid WebSocket handshaked response: 'Upgrade' header value must be 'websocket'");
                        break;
                    }

                    upgrade = true;
                }
                else if (key == "Sec-WebSocket-Accept")
                {
                    // Calculate the original WebSocket hash
                    String wskey = Convert.ToBase64String(Encoding.UTF8.GetBytes(id.ToString())) + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
                    String wshash;
                    using (SHA1Managed sha1 = new SHA1Managed())
                    {
                        wshash = Encoding.UTF8.GetString(sha1.ComputeHash(Encoding.UTF8.GetBytes(wskey)));
                    }

                    // Get the received WebSocket hash
                    wskey = Encoding.UTF8.GetString(Convert.FromBase64String(value));

                    // Compare original and received hashes
                    if (String.Compare(wskey, wshash, StringComparison.InvariantCulture) != 0)
                    {
                        error = true;
                        _wsHandler.OnWsError("Invalid WebSocket handshaked response: 'Sec-WebSocket-Accept' value validation failed");
                        break;
                    }

                    accept = true;
                }
            }

            // Failed to perform WebSocket handshake
            if (!accept || !connection || !upgrade)
            {
                if (!error)
                {
                    _wsHandler.OnWsError("Invalid WebSocket response");
                }

                return(false);
            }

            // WebSocket successfully handshaked!
            WsHandshaked = true;
            IRandom random = RandomUtils.Create();

            random.NextBytes(WsSendMask);
            _wsHandler.OnWsConnected(response);

            return(true);
        }
Ejemplo n.º 16
0
        public static System.Int64 GetInt64(IRandom rand, 
											System.Int64 min = System.Int64.MinValue,
											System.Int64 max = System.Int64.MaxValue)
        {
            byte[] buffer = new byte[8];
            rand.NextBytes(buffer);

            System.Int64 result = System.BitConverter.ToInt64(buffer, 0);

            if(result < min)
                return min;
            else if(result >= max)
                return max - 1;
            else
                return result;
        }
 public static byte NextByte(this IRandom random) => random.NextBytes(1)[0];
 public static ushort NextUInt16(this IRandom random) => BitConverter.ToUInt16(random.NextBytes(2), 0);
 public static uint NextUInt32(this IRandom random) => BitConverter.ToUInt32(random.NextBytes(4), 0);
 public static ulong NextUInt64(this IRandom random) => BitConverter.ToUInt64(random.NextBytes(8), 0);
        private static double MeasureChiSquared(IRandom random, int rounds)
        {
            var counts = new int[256];

            var bs = new byte[256];
            for (var i = 0; i < rounds; ++i)
            {
                random.NextBytes(bs);

                for (var b = 0; b < 256; ++b)
                {
                    ++counts[bs[b]];
                }
            }

            var mask = SecureRandom.GetSeed(1)[0];
            for (var i = 0; i < rounds; ++i)
            {
                random.NextBytes(bs);

                for (var b = 0; b < 256; ++b)
                {
                    ++counts[bs[b] ^ mask];
                }

                ++mask;
            }

            var shift = SecureRandom.GetSeed(1)[0];
            for (var i = 0; i < rounds; ++i)
            {
                random.NextBytes(bs);

                for (var b = 0; b < 256; ++b)
                {
                    ++counts[(byte)(bs[b] + shift)];
                }

                ++shift;
            }

            var total = 3 * rounds;

            double chi2 = 0;
            for (var k = 0; k < counts.Length; ++k)
            {
                var diff = ((double)counts[k]) - total;
                var diff2 = diff * diff;

                chi2 += diff2;
            }

            chi2 /= total;

            return chi2;
        }
Ejemplo n.º 22
0
 public void NextBytes()
 {
     byte[] bytes = new byte[42];
     _random.NextBytes(bytes);
 }