System.Random.NextBytes(byte[])

Here are the examples of the csharp api System.Random.NextBytes(byte[]) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

1021 Examples 7

19 View Source File : RandomHelper.cs
License : MIT License
Project Creator : 1996v

public static object RandomValue(this Type t, bool stringValueAllowEmpty = true)
        {
            if (t.IsPrimitive)
            {
                if (t == typeof(byte))
                {
                    return (byte)(Rand.Next(byte.MaxValue - byte.MinValue + 1) + byte.MinValue);
                }

                if (t == typeof(sbyte))
                {
                    return (sbyte)(Rand.Next(sbyte.MaxValue - sbyte.MinValue + 1) + sbyte.MinValue);
                }

                if (t == typeof(short))
                {
                    return (short)(Rand.Next(short.MaxValue - short.MinValue + 1) + short.MinValue);
                }

                if (t == typeof(ushort))
                {
                    return (ushort)(Rand.Next(ushort.MaxValue - ushort.MinValue + 1) + ushort.MinValue);
                }

                if (t == typeof(int))
                {
                    var bytes = new byte[4];
                    Rand.NextBytes(bytes);

                    return BitConverter.ToInt32(bytes, 0);
                }

                if (t == typeof(uint))
                {
                    var bytes = new byte[4];
                    Rand.NextBytes(bytes);

                    return BitConverter.ToUInt32(bytes, 0);
                }

                if (t == typeof(long))
                {
                    var bytes = new byte[8];
                    Rand.NextBytes(bytes);

                    return BitConverter.ToInt64(bytes, 0);
                }

                if (t == typeof(ulong))
                {
                    var bytes = new byte[8];
                    Rand.NextBytes(bytes);

                    return BitConverter.ToUInt64(bytes, 0);
                }

                if (t == typeof(float))
                {
                    var bytes = new byte[4];
                    Rand.NextBytes(bytes);

                    var f = BitConverter.ToSingle(bytes, 0);
                    if (float.IsNaN(f))
                        f = (float)RandomValue<short>();
                    return f;
                }

                if (t == typeof(double))
                {
                    var bytes = new byte[8];
                    Rand.NextBytes(bytes);

                    var d = BitConverter.ToDouble(bytes, 0);
                    if (double.IsNaN(d))
                        d = (double)RandomValue<short>();
                    return d;
                }

                if (t == typeof(char))
                {
                    var roll = Rand.Next(ASCII.Length);

                    return ASCII[roll];
                }

                if (t == typeof(bool))
                {
                    return (Rand.Next(2) == 1);
                }

                throw new InvalidOperationException();
            }

            if (t == typeof(decimal))
            {
                return new decimal((int)typeof(int).RandomValue(), (int)typeof(int).RandomValue(), (int)typeof(int).RandomValue(), false, 28);
            }

            if (t == typeof(string))
            {
                int start = stringValueAllowEmpty ? 0 : 1;
                var len = Rand.Next(start, 28);
                var c = new char[len];
                for (var i = 0; i < c.Length; i++)
                {
                    c[i] = (char)typeof(char).RandomValue();
                }

                return new string(c);
            }

            if (t == typeof(DateTime))
            {
                var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

                var bytes = new byte[4];
                Rand.NextBytes(bytes);

                var secsOffset = BitConverter.ToInt32(bytes, 0);

                var retDate = epoch.AddSeconds(secsOffset);

                return retDate;
            }

            if (t == typeof(TimeSpan))
            {
                return new TimeSpan(RandomValue<DateTime>().Ticks);
            }

            if (t == typeof(DataTable))
            {
                DataTable dt = new DataTable();
                int coluCount = Rand.Next(10, 30);
                for (int i = 0; i < coluCount; i++)
                {
                    dt.Columns.Add(RandomHelper.RandomValue<string>(false), typeof(object));
                }
                int rowCount = Rand.Next(20, 50);
                for (int i = 0; i < rowCount; i++)
                {
                    var row = new object[coluCount];
                    for (int zi = 0; zi < coluCount; zi++)
                    {
                        row[zi] = RandomHelper.RandomValue<object>();
                    }
                    dt.Rows.Add(row);
                }
                return dt;
            }

            if (t.IsNullable())
            {
                // leave it unset
                if (Rand.Next(2) == 0)
                {
                    // null!
                    return Activator.CreateInstance(t);
                }

                var underlying = Nullable.GetUnderlyingType(t);
                var val = underlying.RandomValue(stringValueAllowEmpty);

                var cons = t.GetConstructor(new[] { underlying });

                return cons.Invoke(new object[] { val });
            }

            if (t.IsEnum)
            {
                var allValues = Enum.GetValues(t);
                var ix = Rand.Next(allValues.Length);

                return allValues.GetValue(ix);
            }

            if (t.IsArray)
            {
                var valType = t.GetElementType();
                var len = Rand.Next(20, 50);
                var ret = Array.CreateInstance(valType, len);
                //var add = t.GetMethod("SetValue");
                for (var i = 0; i < len; i++)
                {
                    var elem = valType.RandomValue(stringValueAllowEmpty);
                    ret.SetValue(elem, i);
                }

                return ret;
            }

            if (t.IsGenericType)
            {
                var defind = t.GetGenericTypeDefinition();
                if (defind == typeof(HashSet<>))
                {
                    var valType = t.GetGenericArguments()[0];
                    var ret = Activator.CreateInstance(t);
                    var add = t.GetMethod("Add");
                    var contains = t.GetMethod("Contains");

                    var len = Rand.Next(20, 50);
                    for (var i = 0; i < len; i++)
                    {
                        var elem = valType.RandomValue(stringValueAllowEmpty);
                        while (elem == null || (bool)contains.Invoke(ret, new object[] { elem }))
                            elem = valType.RandomValue(stringValueAllowEmpty);
                        add.Invoke(ret, new object[] { elem });
                    }

                    return ret;
                }
                if (defind == typeof(Dictionary<,>))
                {
                    var keyType = t.GetGenericArguments()[0];
                    var valType = t.GetGenericArguments()[1];
                    var ret = Activator.CreateInstance(t);
                    var add = t.GetMethod("Add");
                    var contains = t.GetMethod("ContainsKey");

                    var len = Rand.Next(20, 50);
                    if (keyType == typeof(Boolean))
                        len = 2;
                    for (var i = 0; i < len; i++)
                    {
                        var val = valType.RandomValue(stringValueAllowEmpty);
                        var key = keyType.RandomValue(stringValueAllowEmpty);
                        while (key == null || (bool)contains.Invoke(ret, new object[] { key }))
                            key = keyType.RandomValue(stringValueAllowEmpty);
                        add.Invoke(ret, new object[] { key, val });
                    }

                    return ret;
                }
                if (defind == typeof(List<>))
                {
                    var valType = t.GetGenericArguments()[0];
                    var ret = Activator.CreateInstance(t);
                    var add = t.GetMethod("Add");

                    var len = Rand.Next(20, 50);
                    for (var i = 0; i < len; i++)
                    {
                        var elem = valType.RandomValue(stringValueAllowEmpty);
                        add.Invoke(ret, new object[] { elem });
                    }

                    return ret;
                }
                if (defind == typeof(ArraySegment<>))
                {
                    var valType = t.GetGenericArguments()[0];
                    var ary = valType.MakeArrayType().RandomValue(stringValueAllowEmpty);
                    var lenT = ary.GetType().GetProperty("Length");
                    var offset = Rand.Next(0, (int)lenT.GetValue(ary) - 1);
                    var len = (int)lenT.GetValue(ary) - offset;

                    return Activator.CreateInstance(t, ary, offset, len);
                }
            }

            if (t == typeof(Guid))
                return Guid.NewGuid();

            if (t == typeof(object))
            {
                var code = Rand.Next(0, 9);
                switch (code)
                {
                    case 0:
                        return RandomValue<int>();
                    case 1:
                        return RandomValue<long>();
                    case 2:
                        return RandomValue<Char>();
                    case 3:
                        return RandomValue<DateTime>();
                    case 4:
                        return RandomValue<string>(stringValueAllowEmpty);
                    case 5:
                        return RandomValue<Guid>();
                    case 6:
                        return RandomValue<decimal>();
                    case 7:
                        return RandomValue<double>();
                    case 8:
                        return RandomValue<float>();
                    default:
                        return RandomValue<short>();
                }
            }

            //model
            var retObj = Activator.CreateInstance(t);
            foreach (var p in t.GetFields())
            {
                //if (Rand.Next(5) == 0) continue;

                var fieldType = p.FieldType;

                p.SetValue(retObj, fieldType.RandomValue(stringValueAllowEmpty));
            }

            foreach (var p in t.GetProperties())
            {
                //if (Rand.Next(5) == 0) continue;
                if (p.CanWrite && p.CanRead)
                {
                    var fieldType = p.PropertyType;

                    p.SetValue(retObj, fieldType.RandomValue(stringValueAllowEmpty));
                }
            }

            return retObj;
        }

19 View Source File : RandomHelper.cs
License : MIT License
Project Creator : 1996v

public static object RandomValue(this Type t, bool stringValueAllowEmpty = true)
        {
            if (t.IsPrimitive)
            {
                if (t == typeof(byte))
                {
                    return (byte)(Rand.Next(byte.MaxValue - byte.MinValue + 1) + byte.MinValue);
                }

                if (t == typeof(sbyte))
                {
                    return (sbyte)(Rand.Next(sbyte.MaxValue - sbyte.MinValue + 1) + sbyte.MinValue);
                }

                if (t == typeof(short))
                {
                    return (short)(Rand.Next(short.MaxValue - short.MinValue + 1) + short.MinValue);
                }

                if (t == typeof(ushort))
                {
                    return (ushort)(Rand.Next(ushort.MaxValue - ushort.MinValue + 1) + ushort.MinValue);
                }

                if (t == typeof(int))
                {
                    var bytes = new byte[4];
                    Rand.NextBytes(bytes);

                    return BitConverter.ToInt32(bytes, 0);
                }

                if (t == typeof(uint))
                {
                    var bytes = new byte[4];
                    Rand.NextBytes(bytes);

                    return BitConverter.ToUInt32(bytes, 0);
                }

                if (t == typeof(long))
                {
                    var bytes = new byte[8];
                    Rand.NextBytes(bytes);

                    return BitConverter.ToInt64(bytes, 0);
                }

                if (t == typeof(ulong))
                {
                    var bytes = new byte[8];
                    Rand.NextBytes(bytes);

                    return BitConverter.ToUInt64(bytes, 0);
                }

                if (t == typeof(float))
                {
                    var bytes = new byte[4];
                    Rand.NextBytes(bytes);

                    var f = BitConverter.ToSingle(bytes, 0);
                    if (float.IsNaN(f))
                        f = (float)RandomValue<short>();
                    return f;
                }

                if (t == typeof(double))
                {
                    var bytes = new byte[8];
                    Rand.NextBytes(bytes);

                    var d= BitConverter.ToDouble(bytes, 0);
                    if (double.IsNaN(d))
                        d = (double)RandomValue<short>();
                    return d;
                }

                if (t == typeof(char))
                {
                    var roll = Rand.Next(ASCII.Length);

                    return ASCII[roll];
                }

                if (t == typeof(bool))
                {
                    return (Rand.Next(2) == 1);
                }

                throw new InvalidOperationException();
            }

            if (t == typeof(decimal))
            {
                return new decimal((int)typeof(int).RandomValue(), (int)typeof(int).RandomValue(), (int)typeof(int).RandomValue(), false, 28);
            }

            if (t == typeof(string))
            {
                int start = stringValueAllowEmpty ? 0 : 1;
                var len = Rand.Next(start, 40);
                var c = new char[len];
                for (var i = 0; i < c.Length; i++)
                {
                    c[i] = (char)typeof(char).RandomValue();
                }

                return new string(c);
            }

            if (t == typeof(DateTime))
            {
                var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

                var bytes = new byte[4];
                Rand.NextBytes(bytes);

                var secsOffset = BitConverter.ToInt32(bytes, 0);

                var retDate = epoch.AddSeconds(secsOffset);

                return retDate;
            }

            if (t == typeof(TimeSpan))
            {
                return new TimeSpan(RandomValue<DateTime>().Ticks);
            }

            if (t == typeof(DataTable))
            {
                DataTable dt = new DataTable();
                int coluCount = Rand.Next(10, 30);
                for (int i = 0; i < coluCount; i++)
                {
                    string n = RandomHelper.RandomValue<string>(false);
                    while(dt.Columns.Contains(n))
                        n = RandomHelper.RandomValue<string>(false);
                    dt.Columns.Add(n, typeof(object));
                }
                int rowCount = Rand.Next(20, 50);
                for (int i = 0; i < rowCount; i++)
                {
                    var row = new object[coluCount];
                    for (int zi = 0; zi < coluCount; zi++)
                    {
                        row[zi] = RandomHelper.RandomValue<object>();
                    }
                    dt.Rows.Add(row);
                }
                return dt;
            }

            if (t.IsNullable())
            {
                // leave it unset
                if (Rand.Next(2) == 0)
                {
                    // null!
                    return Activator.CreateInstance(t);
                }

                var underlying = Nullable.GetUnderlyingType(t);
                var val = underlying.RandomValue(stringValueAllowEmpty);

                var cons = t.GetConstructor(new[] { underlying });

                return cons.Invoke(new object[] { val });
            }

            if (t.IsEnum)
            {
                var allValues = Enum.GetValues(t);
                var ix = Rand.Next(allValues.Length);

                return allValues.GetValue(ix);
            }

            if (t.IsArray)
            {
                var valType = t.GetElementType();
                var len = Rand.Next(20, 50);
                var ret = Array.CreateInstance(valType, len);
                //var add = t.GetMethod("SetValue");
                for (var i = 0; i < len; i++)
                {
                    var elem = valType.RandomValue(stringValueAllowEmpty);
                    ret.SetValue(elem, i);
                }

                return ret;
            }

            if (t.IsGenericType)
            {
                var defind = t.GetGenericTypeDefinition();
                if (defind == typeof(HashSet<>))
                {
                    var valType = t.GetGenericArguments()[0];
                    var ret = Activator.CreateInstance(t);
                    var add = t.GetMethod("Add");
                    var contains = t.GetMethod("Contains");

                    var len = Rand.Next(20, 50);
                    for (var i = 0; i < len; i++)
                    {
                        var elem = valType.RandomValue(stringValueAllowEmpty);
                        while (elem == null || (bool)contains.Invoke(ret, new object[] { elem }))
                            elem = valType.RandomValue(stringValueAllowEmpty);
                        add.Invoke(ret, new object[] { elem });
                    }

                    return ret;
                }
                if (defind == typeof(Dictionary<,>))
                {
                    var keyType = t.GetGenericArguments()[0];
                    var valType = t.GetGenericArguments()[1];
                    var ret = Activator.CreateInstance(t);
                    var add = t.GetMethod("Add");
                    var contains = t.GetMethod("ContainsKey");

                    var len = Rand.Next(20, 50);
                    if (keyType == typeof(Boolean))
                        len = 2;
                    for (var i = 0; i < len; i++)
                    {
                        var val = valType.RandomValue(stringValueAllowEmpty);
                        var key = keyType.RandomValue(stringValueAllowEmpty);
                       

                        while (key == null || (bool)contains.Invoke(ret, new object[] { key }))
                            key = keyType.RandomValue(stringValueAllowEmpty);
                        add.Invoke(ret, new object[] { key, val });
                    }

                    return ret;
                }
                if (defind == typeof(List<>))
                {
                    var valType = t.GetGenericArguments()[0];
                    var ret = Activator.CreateInstance(t);
                    var add = t.GetMethod("Add");

                    var len = Rand.Next(20, 50);
                    for (var i = 0; i < len; i++)
                    {
                        var elem = valType.RandomValue(stringValueAllowEmpty);
                        add.Invoke(ret, new object[] { elem });
                    }

                    return ret;
                }
                if (defind == typeof(ArraySegment<>))
                {
                    var valType = t.GetGenericArguments()[0];
                    var ary = valType.MakeArrayType().RandomValue(stringValueAllowEmpty);
                    var lenT = ary.GetType().GetProperty("Length");
                    var offset = Rand.Next(0, (int)lenT.GetValue(ary) - 1);
                    var len = (int)lenT.GetValue(ary) - offset;

                    return Activator.CreateInstance(t, ary, offset, len);
                }
            }

            if (t == typeof(Guid))
                return Guid.NewGuid();

            if (t == typeof(object))
            {
                var code = Rand.Next(0, 9);
                switch (code)
                {
                    case 0:
                        return RandomValue<int>();
                    case 1:
                        return RandomValue<long>();
                    case 2:
                        return RandomValue<Char>();
                    case 3:
                        return RandomValue<DateTime>();
                    case 4:
                        return RandomValue<string>(stringValueAllowEmpty);
                    case 5:
                        return RandomValue<Guid>();
                    case 6:
                        return RandomValue<decimal>();
                    case 7:
                        return RandomValue<double>();
                    case 8:
                        return RandomValue<float>();
                    default:
                        return RandomValue<short>();
                }
            }

            //model
            var retObj = Activator.CreateInstance(t);
            foreach (var p in t.GetFields())
            {
                //if (Rand.Next(5) == 0) continue;

                var fieldType = p.FieldType;

                p.SetValue(retObj, fieldType.RandomValue(stringValueAllowEmpty));
            }

            foreach (var p in t.GetProperties())
            {
                //if (Rand.Next(5) == 0) continue;
                if (p.CanWrite && p.CanRead)
                {
                    var fieldType = p.PropertyType;

                    p.SetValue(retObj, fieldType.RandomValue(stringValueAllowEmpty));
                }
            }

            return retObj;
        }

19 View Source File : Form1.cs
License : Mozilla Public License 2.0
Project Creator : 1M50RRY

private static string Pump()
        {
            Random rnd = new Random();
            int size = rnd.Next(1000, 1000000);
            byte[] gen = new byte[size];
            rnd.NextBytes(gen);
            string filename = "Garbage.bin";
            File.WriteAllBytes(filename, gen);
            return filename;
        }

19 View Source File : Util.cs
License : MIT License
Project Creator : 499116344

public static byte[] RandomKey()
        {
            var key = new byte[QQGlobal.QQLengthKey];
            new Random().NextBytes(key);
            return key;
        }

19 View Source File : Util.cs
License : MIT License
Project Creator : 499116344

public static byte[] RandomKey(int length)
        {
            var key = new byte[length];
            new Random().NextBytes(key);
            return key;
        }

19 View Source File : TestUnlimitedBuffer.cs
License : MIT License
Project Creator : a1q123456

[TestMethod]
        public void TestBufferSegmentSize()
        {
            var random = new Random();

            replacedert.ThrowsException<ArgumentOutOfRangeException>(() => new ByteBuffer(0));

            for (int i = 0; i < 10000; i++)
            {
                var size = random.Next(1, 500);
                var len1 = random.Next(0, 100);
                var len2 = random.Next(0, 200);
                var buffer = new ByteBuffer(size);

                var bytes1 = new byte[len1];
                var bytes2 = new byte[len2];
                random.NextBytes(bytes1);
                random.NextBytes(bytes2);
                buffer.WriteToBuffer(bytes1);
                buffer.WriteToBuffer(bytes2);

                var length = buffer.Length;

                replacedert.AreEqual(length, len1 + len2);

                var outBuffer = ArrayPool<byte>.Shared.Rent(length);
                buffer.TakeOutMemory(outBuffer);
                replacedert.IsTrue(outBuffer.replacedpan(0, len1).SequenceEqual(bytes1));
                replacedert.IsTrue(outBuffer.replacedpan(len1, len2).SequenceEqual(bytes2));
            }
        }

19 View Source File : TestUnlimitedBuffer.cs
License : MIT License
Project Creator : a1q123456

[TestMethod]
        public void TestBufferLength()
        {
            var random = new Random();

            for (int i = 0; i < 1000; i++)
            {
                var len1 = random.Next(0, 3000);
                var len2 = random.Next(0, 3000);
                var bytes1 = new byte[len1];
                var bytes2 = new byte[len2];

                random.NextBytes(bytes1);
                random.NextBytes(bytes2);

                var buffer = new ByteBuffer();
                buffer.WriteToBuffer(bytes1);
                buffer.WriteToBuffer(bytes2);
                replacedert.AreEqual(len1 + len2, buffer.Length);
            }
        }

19 View Source File : TestUnlimitedBuffer.cs
License : MIT License
Project Creator : a1q123456

[TestMethod]
        public void TestWriteToBuffer4DifferentBufferSegmentSize()
        {
            for (int i = 0; i < 10000; i++)
            {
                var random = new Random();
                var buffer = new ByteBuffer(random.Next(1, 3000));
                var bytes1 = new byte[1024];
                var data = (byte)random.Next(byte.MinValue, byte.MaxValue);
                random.NextBytes(bytes1);
                buffer.WriteToBuffer(bytes1);
                buffer.WriteToBuffer(data);

                var length = buffer.Length;
                var outBuffer = ArrayPool<byte>.Shared.Rent(length);
                buffer.TakeOutMemory(outBuffer);
                replacedert.IsTrue(outBuffer.replacedpan(0, 1024).SequenceEqual(bytes1));
                replacedert.AreEqual(outBuffer[1024], data);
            }
        }

19 View Source File : TestUnlimitedBuffer.cs
License : MIT License
Project Creator : a1q123456

[TestMethod]
        public void TestWriteToBuffer3DifferentBufferSegmentSize()
        {
            for (int i = 0; i < 10000; i++)
            {
                var random = new Random();
                var buffer = new ByteBuffer(random.Next(1, 3000));
                var bytes1 = new byte[3];
                var data = (byte)random.Next(byte.MinValue, byte.MaxValue);
                random.NextBytes(bytes1);
                buffer.WriteToBuffer(bytes1);
                buffer.WriteToBuffer(data);

                var length = buffer.Length;
                var outBuffer = ArrayPool<byte>.Shared.Rent(length);
                buffer.TakeOutMemory(outBuffer);
                replacedert.IsTrue(outBuffer.replacedpan(0, 3).SequenceEqual(bytes1));
                replacedert.AreEqual(outBuffer[3], data);
            }
        }

19 View Source File : TestUnlimitedBuffer.cs
License : MIT License
Project Creator : a1q123456

[TestMethod]
        public void TestWriteToBuffer4()
        {
            var buffer = new ByteBuffer();
            var random = new Random();
            var bytes1 = new byte[1024];
            var data = (byte)random.Next(byte.MinValue, byte.MaxValue);
            random.NextBytes(bytes1);
            buffer.WriteToBuffer(bytes1);
            buffer.WriteToBuffer(data);

            var length = buffer.Length;
            var outBuffer = ArrayPool<byte>.Shared.Rent(length);
            buffer.TakeOutMemory(outBuffer);
            replacedert.IsTrue(outBuffer.replacedpan(0, 1024).SequenceEqual(bytes1));
            replacedert.AreEqual(outBuffer[1024], data);
        }

19 View Source File : TestUnlimitedBuffer.cs
License : MIT License
Project Creator : a1q123456

[TestMethod]
        public void TestWriteToBuffer3()
        {
            var buffer = new ByteBuffer();
            var random = new Random();
            var bytes1 = new byte[3];
            var data = (byte)random.Next(byte.MinValue, byte.MaxValue);
            random.NextBytes(bytes1);
            buffer.WriteToBuffer(bytes1);
            buffer.WriteToBuffer(data);

            var length = buffer.Length;
            var outBuffer = ArrayPool<byte>.Shared.Rent(length);
            buffer.TakeOutMemory(outBuffer);
            replacedert.IsTrue(outBuffer.replacedpan(0, 3).SequenceEqual(bytes1));
            replacedert.AreEqual(outBuffer[3], data);
        }

19 View Source File : TestUnlimitedBuffer.cs
License : MIT License
Project Creator : a1q123456

[TestMethod]
        public void TestWriteToBuffer1DifferentBufferSegmentSize()
        {
            for (int i = 0; i < 10000; i++)
            {
                var random = new Random();
                var buffer = new ByteBuffer(random.Next(1, 3000));
                var bytes1 = new byte[3];
                var bytes2 = new byte[7];
                random.NextBytes(bytes1);
                random.NextBytes(bytes2);
                buffer.WriteToBuffer(bytes1);
                buffer.WriteToBuffer(bytes2);

                var length = buffer.Length;
                var outBuffer = ArrayPool<byte>.Shared.Rent(length);
                buffer.TakeOutMemory(outBuffer);
                replacedert.IsTrue(outBuffer.replacedpan(0, 3).SequenceEqual(bytes1));
                replacedert.IsTrue(outBuffer.replacedpan(3, 7).SequenceEqual(bytes2));
            }
        }

19 View Source File : TestUnlimitedBuffer.cs
License : MIT License
Project Creator : a1q123456

[TestMethod]
        public void TestWriteToBuffer2()
        {
            var buffer = new ByteBuffer();
            var random = new Random();
            var bytes1 = new byte[4000];
            var bytes2 = new byte[3001];
            random.NextBytes(bytes1);
            random.NextBytes(bytes2);
            buffer.WriteToBuffer(bytes1);
            buffer.WriteToBuffer(bytes2);

            var length = buffer.Length;
            var outBuffer = ArrayPool<byte>.Shared.Rent(length);
            buffer.TakeOutMemory(outBuffer);
            var seq = outBuffer.replacedpan(0, 4000);
            var seq2 = outBuffer.replacedpan(4000, 3001).ToArray();
            replacedert.IsTrue(seq.SequenceEqual(bytes1));
            replacedert.IsTrue(seq2.SequenceEqual(bytes2));
            outBuffer.replacedpan().Clear();
            buffer.TakeOutMemory(outBuffer);
            replacedert.IsFalse(outBuffer.Any(b => b != 0));
        }

19 View Source File : TestUnlimitedBuffer.cs
License : MIT License
Project Creator : a1q123456

[TestMethod]
        public void TestClearAndCopyToDifferentBufferSegmentSize()
        {
            var random = new Random();
            var buffer = new ByteBuffer(random.Next(1, 3000));
            var bytes1 = new byte[4000];
            random.NextBytes(bytes1);
            buffer.WriteToBuffer(bytes1);

            var length = buffer.Length;
            var outBuffer = ArrayPool<byte>.Shared.Rent(length);
            buffer.TakeOutMemory(outBuffer);
            outBuffer.replacedpan().Clear();
            buffer.TakeOutMemory(outBuffer);
            replacedert.IsFalse(outBuffer.Any(b => b != 0));
        }

19 View Source File : TestUnlimitedBuffer.cs
License : MIT License
Project Creator : a1q123456

[TestMethod]
        public void TestClearAndCopyTo()
        {
            var buffer = new ByteBuffer();
            var random = new Random();
            var bytes1 = new byte[4000];
            random.NextBytes(bytes1);
            buffer.WriteToBuffer(bytes1);

            var length = buffer.Length;
            var outBuffer = ArrayPool<byte>.Shared.Rent(length);
            buffer.TakeOutMemory(outBuffer);
            outBuffer.replacedpan().Clear();
            buffer.TakeOutMemory(outBuffer);
            replacedert.IsFalse(outBuffer.Any(b => b != 0));
        }

19 View Source File : TestUnlimitedBuffer.cs
License : MIT License
Project Creator : a1q123456

[TestMethod]
        public void TestBufferLengthDifferentBufferSegmentSize()
        {
            var random = new Random();

            for (int i = 0; i < 1000; i++)
            {
                var len1 = random.Next(0, 3000);
                var len2 = random.Next(0, 3000);
                var bytes1 = new byte[len1];
                var bytes2 = new byte[len2];

                random.NextBytes(bytes1);
                random.NextBytes(bytes2);

                var buffer = new ByteBuffer(random.Next(10, 3000));
                buffer.WriteToBuffer(bytes1);
                buffer.WriteToBuffer(bytes2);
                replacedert.AreEqual(len1 + len2, buffer.Length);
            }
        }

19 View Source File : TestUnlimitedBuffer.cs
License : MIT License
Project Creator : a1q123456

[TestMethod]
        public void TestWriteToBuffer5DifferentBufferSegmentSize()
        {
            for (int i = 0; i < 10000; i++)
            {
                var random = new Random();
                var buffer = new ByteBuffer(512);
                var bytes1 = new byte[4096];
                var data = (byte)random.Next(byte.MinValue, byte.MaxValue);
                random.NextBytes(bytes1);
                buffer.WriteToBuffer(bytes1);
                buffer.WriteToBuffer(data);

                var length = buffer.Length;
                var outBuffer = ArrayPool<byte>.Shared.Rent(length);
                var test1 = new byte[2];
                var test2 = new byte[3];
                var test3 = new byte[512];
                var test4 = new byte[1024];
                buffer.TakeOutMemory(test1.replacedpan());
                buffer.TakeOutMemory(test2.replacedpan());
                buffer.TakeOutMemory(test3);
                buffer.TakeOutMemory(test4);
                buffer.TakeOutMemory(outBuffer);
                replacedert.IsTrue(test1.replacedpan().SequenceEqual(bytes1.replacedpan(0, 2)));
                replacedert.IsTrue(test2.replacedpan().SequenceEqual(bytes1.replacedpan(2, 3)));
                replacedert.IsTrue(test3.replacedpan().SequenceEqual(bytes1.replacedpan(5, 512)));
                replacedert.IsTrue(test4.replacedpan().SequenceEqual(bytes1.replacedpan(517, 1024)));
                replacedert.IsTrue(outBuffer.replacedpan(0, 4096 - 5 - 512 - 1024).SequenceEqual(bytes1.replacedpan(517 + 1024)));
            }
        }

19 View Source File : TestUnlimitedBuffer.cs
License : MIT License
Project Creator : a1q123456

[TestMethod]
        public void TestWriteToBuffer1()
        {
            var buffer = new ByteBuffer();
            var random = new Random();
            var bytes1 = new byte[3];
            var bytes2 = new byte[7];
            random.NextBytes(bytes1);
            random.NextBytes(bytes2);
            buffer.WriteToBuffer(bytes1);
            buffer.WriteToBuffer(bytes2);

            var length = buffer.Length;
            var outBuffer = ArrayPool<byte>.Shared.Rent(length);
            buffer.TakeOutMemory(outBuffer);
            replacedert.IsTrue(outBuffer.replacedpan(0, 3).SequenceEqual(bytes1));
            replacedert.IsTrue(outBuffer.replacedpan(3, 7).SequenceEqual(bytes2));
        }

19 View Source File : HandshakeContext.cs
License : MIT License
Project Creator : a1q123456

private bool ProcessHandshakeC0C1(ReadOnlySequence<byte> buffer, ref int consumed)
        {
            if (buffer.Length - consumed < 1537)
            {
                return false;
            }
            var arr = _arrayPool.Rent(1537);
            try
            {
                buffer.Slice(consumed, 9).CopyTo(arr);
                consumed += 9;
                var version = arr[0];

                if (version < 3)
                {
                    throw new NotSupportedException();
                }
                if (version > 31)
                {
                    throw new ProtocolViolationException();
                }

                _readerTimestampEpoch = NetworkBitConverter.ToUInt32(arr.replacedpan(1, 4));
                _writerTimestampEpoch = 0;
                _s1Data = _arrayPool.Rent(1528);
                _random.NextBytes(_s1Data.replacedpan(0, 1528));

                // s0s1
                arr.replacedpan().Clear();
                arr[0] = 3;
                NetworkBitConverter.TryGetBytes(_writerTimestampEpoch, arr.replacedpan(1, 4));
                _s1Data.replacedpan(0, 1528).CopyTo(arr.replacedpan(9));
                _ = _ioPipeline.SendRawData(arr.AsMemory(0, 1537));

                // s2
                NetworkBitConverter.TryGetBytes(_readerTimestampEpoch, arr.replacedpan(0, 4));
                NetworkBitConverter.TryGetBytes((uint)0, arr.replacedpan(4, 4));

                _ = _ioPipeline.SendRawData(arr.AsMemory(0, 1536));

                buffer.Slice(consumed, 1528).CopyTo(arr.replacedpan(8));
                consumed += 1528;

                _ioPipeline.NextProcessState = ProcessState.HandshakeC2;
                return true;
            }
            finally
            {
                _arrayPool.Return(arr);
            }
        }

19 View Source File : CustomOverviewViewModel.cs
License : MIT License
Project Creator : ABTSoftware

private void Initialize()
        {
            RenderableSeriesViewModels = new ObservableCollection<IRenderableSeriesViewModel>();
            var random = new Random(0);
            var generator = new RandomWalkGenerator();

            for (int i = 0; i < SeriesCount; i++)
            {
                var dataSeries = new UniformXyDataSeries<double>();
                var someData = generator.GetRandomWalkYData(PointCount);
                
                generator.Reset();
                dataSeries.Append(someData);

                var rgb = new byte[3];
                random.NextBytes(rgb);

                RenderableSeriesViewModels.Add(new LineRenderableSeriesViewModel
                {
                    DataSeries = dataSeries,
                    AntiAliasing = false,
                    Stroke = Color.FromArgb(255, rgb[0], rgb[1], rgb[2])
                });
            }
        }

19 View Source File : LineSeriesSource.cs
License : MIT License
Project Creator : ABTSoftware

private static void OnDataSeriesDependencyPropertyChanged(DependencyObject d,
                                                                  DependencyPropertyChangedEventArgs e)
        {
            var sciChartSurface = d as SciChartSurface;
            if (sciChartSurface == null) return;

            if (e.NewValue == null)
            {
                sciChartSurface.RenderableSeries.Clear();
                return;
            }

            using (sciChartSurface.SuspendUpdates())
            {
                sciChartSurface.RenderableSeries.Clear();

                var random = new Random();
                var itr = (IEnumerable<IDataSeries>)e.NewValue;
                var renderSeries = new List<IRenderableSeries>();
                foreach (var dataSeries in itr)
                {
                    if (dataSeries == null) continue;

                    var rgb = new byte[3];
                    random.NextBytes(rgb);
                    var renderableSeries = new FastLineRenderableSeries()
                    {
                        AntiAliasing = true,
                        Stroke = Color.FromArgb(255, rgb[0], rgb[1], rgb[2]),
                        DataSeries = dataSeries,
                        StrokeThickness = 1,
                    };

                    renderSeries.Add(renderableSeries);
                }

                sciChartSurface.RenderableSeries = new ObservableCollection<IRenderableSeries>(renderSeries);
            }
        }

19 View Source File : OffScreenExportView.xaml.cs
License : MIT License
Project Creator : ABTSoftware

private IEnumerable<SciChartSurface> GetMultippleCharts()
        {
            var collectionToReturn = new List<SciChartSurface>();
            var random = new Random();

            for (var i = 0; i < 5; i++)
            {
                var b = new byte[3];
                random.NextBytes(b);
                var surface = new SciChartSurface
                {
                    XAxis = new NumericAxis { GrowBy = new DoubleRange(0.1, 0.1) },
                    YAxis = new NumericAxis { GrowBy = new DoubleRange(0.1, 0.1) },

                    // Add RenderableSerieses
                    RenderableSeries = new ObservableCollection<IRenderableSeries>
                    {
                        new FastLineRenderableSeries
                        {
                            DataSeries = GetLineDataseries(0.1, 0.1, 3000),
                            Stroke = Color.FromRgb(b[0], b[1], b[2]),
                            StrokeThickness = random.Next(12),
                        }
                    },
                    // Add Annotations
                    Annotations = new AnnotationCollection()
                    {
                        new BoxAnnotation()
                        {
                            X1 = 2,
                            X2 = 8,
                            Y1 = 0.1,
                            Y2 = 0.3,
                            Background = new SolidColorBrush(Colors.Red),
                        },

                        new VerticalLineAnnotation()
                        {
                            X1 = 3,
                            Stroke = new SolidColorBrush(Colors.Yellow),
                            StrokeThickness = 3,
                            ShowLabel = true,
                            LabelPlacement = LabelPlacement.Axis
                        }
                    },
                };

                collectionToReturn.Add(surface);
            }

            return collectionToReturn;
        }

19 View Source File : LineSeriesSource.cs
License : MIT License
Project Creator : ABTSoftware

private static void OnDataSeriesDependencyPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var sciChartSurface = d as SciChartSurface;
            if (sciChartSurface == null) return;

            if (e.NewValue == null)
            {
                sciChartSurface.RenderableSeries.Clear();
                return;
            }

            using (sciChartSurface.SuspendUpdates())
            {
                sciChartSurface.RenderableSeries.Clear();

                var random = new Random();
                var itr = (IEnumerable<IDataSeries>)e.NewValue;
                var renderSeries = new List<IRenderableSeries>();

                // 1.7.2 specific
                var dataset = new DataSeriesSet<double, double>();

                foreach (var dataSeries in itr)
                {
                    if (dataSeries == null) continue;

                    // 1.7.2 specific 
                    dataset.Add(dataSeries);

                    var rgb = new byte[3];
                    random.NextBytes(rgb);
                    var renderableSeries = new FastLineRenderableSeries()
                    {
                        ResamplingMode = ResamplingMode.MinMax,
                        SeriesColor = Color.FromArgb(255, rgb[0], rgb[1], rgb[2]),
                        DataSeries = dataSeries,
                    };

                    renderSeries.Add(renderableSeries);
                }

                // 1.7.2 specific
                sciChartSurface.DataSet = dataset;

                sciChartSurface.RenderableSeries = new ObservableCollection<IRenderableSeries>(renderSeries);
            }

        }

19 View Source File : FifoLineSeriesSpeedTest.xaml.cs
License : MIT License
Project Creator : ABTSoftware

public void Execute(TestParameters testParameters, TimeSpan duration, Action<double> fpsResult)
        {
            _generator = new RandomLinesGenerator();
            var initialData = _generator.GetRandomLinesSeries(testParameters.PointCount);
            Random random = new Random(); 
            for (int i = 0; i < SeriesCount; i++)
            {
                // Setup
                _xyDataSeries = new XyDataSeries<double, double>() { FifoCapacity = testParameters.PointCount, DataDistributionCalculator = d };
                
                _listSeries.Add(_xyDataSeries);

                var rgb = new byte[3];
                random.NextBytes(rgb);
                _xyDataSeries.Append(initialData.XData, ScaleAndOffset(initialData.YData, 0.1, (double)i*0.2));
                var tmp = new SciChart.Charting.Visuals.RenderableSeries.FastLineRenderableSeries();
                tmp.DataSeries = _xyDataSeries;
                tmp.AntiAliasing = testParameters.AntiAliasing;
                tmp.Stroke  = System.Windows.Media.Color.FromArgb(255, rgb[0], rgb[1], rgb[2]);
                tmp.ResamplingMode = (ResamplingMode)Enum.Parse(typeof(ResamplingMode), testParameters.SamplingMode.ToString());
                sciChart.RenderableSeries.Add(tmp);
            }

            // Execute
           if (testParameters.TestRunner == TestRunnerType.Composition)
               _testRunner = new CompositionTestRunner(duration, OnAppendData, fpsResult);
           else
               _testRunner = new DispatcherTimerRunner(duration, OnAppendData, fpsResult);



           sciChart.Rendered += _testRunner.OnSciChartRendered;
            _testRunner.Run();
        }

19 View Source File : LineSeriesSource.cs
License : MIT License
Project Creator : ABTSoftware

private static void OnDataSeriesDependencyPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var sciChartSurface = d as SciChartSurface;
            if (sciChartSurface == null) return;

            if (e.NewValue == null)
            {
                sciChartSurface.RenderableSeries.Clear();
                return;
            }

            using (sciChartSurface.SuspendUpdates())
            {
                sciChartSurface.RenderableSeries.Clear();

                var random = new Random();
                var itr = (IEnumerable<IDataSeries>)e.NewValue;
                var renderSeries = new List<IRenderableSeries>();

                var strokeThckness = GetStrokeThickness(sciChartSurface);
                var aa = GetAntiAliasing(sciChartSurface);

                foreach (var dataSeries in itr)
                {
                    if (dataSeries == null) continue;
                    
                    var rgb = new byte[3];
                    random.NextBytes(rgb);
                    var renderableSeries = new FastLineRenderableSeries()
                    {
                        ResamplingMode = ResamplingMode.MinMax,
                        StrokeThickness = (int) strokeThckness,
                        Stroke = Color.FromArgb(255, rgb[0], rgb[1], rgb[2]),
                        AntiAliasing = aa,
                        DataSeries = dataSeries,
                    };

                    renderSeries.Add(renderableSeries);
                }

                sciChartSurface.RenderableSeries = new ObservableCollection<IRenderableSeries>(renderSeries);
            }

        }

19 View Source File : StaticRandom.cs
License : GNU General Public License v3.0
Project Creator : AdamWhiteHat

public static void NextBytes(byte[] bytes)
		{
			rand.NextBytes(bytes);
		}

19 View Source File : AudioFileTests.cs
License : MIT License
Project Creator : adlez27

[Fact]
        public void WriteRandom()
        {
            Random rnd = new Random();
            byte[] b = new byte[40000];
            rnd.NextBytes(b);
            af.Write(b,Path.Combine(settings.DestinationFolder, fileName + ".wav"));
        }

19 View Source File : CryptoHelperTests.cs
License : MIT License
Project Creator : AElfProject

[Fact]
        public void Generate_Key_Test()
        {
            var keyPair = CryptoHelper.GenerateKeyPair();
            keyPair.ShouldNotBeNull();
            keyPair.PrivateKey.Length.ShouldBe(32);
            keyPair.PublicKey.Length.ShouldBe(65);

            //invalid key length
            var bytes = new byte[30];
            new Random().NextBytes(bytes);
            replacedert.Throws<InvalidPrivateKeyException>(() => CryptoHelper.FromPrivateKey(bytes));
        }

19 View Source File : ByteArrayHelperTests.cs
License : MIT License
Project Creator : AElfProject

private static byte[] RandomFill(int count)
        {
            byte[] random = new byte[count];

            _rnd.NextBytes(random);

            return random;
        }

19 View Source File : FormatterAndConverterTests.cs
License : MIT License
Project Creator : AElfProject

private static Address GenerateAddress()
        {
            var byteArray = new byte[32];
            new Random().NextBytes(byteArray);

            return Address.FromBytes(byteArray);
        }

19 View Source File : Sr25519Tests.cs
License : Apache License 2.0
Project Creator : ajuna-network

[Test]
        public void Sr25519SignatureTest()
        {
            var miniSecretAlice = new MiniSecret(Utils.HexToByteArray("0xe5be9a5092b81bca64be81d212e7f2f9eba183bb7a90954f7b76361f6edb5c0a"), ExpandMode.Ed25519);
            var keyPairAlice = miniSecretAlice.GetPair();

            var messageLength = _random.Next(10, 200);
            var message = new byte[messageLength];
            _random.NextBytes(message);

            var simpleSign = Schnorrkel.Sr25519v091.SignSimple(keyPairAlice, message);

            replacedert.True(Schnorrkel.Sr25519v091.Verify(simpleSign, keyPairAlice.Public.Key, message));
        }

19 View Source File : Ed25519Tests.cs
License : Apache License 2.0
Project Creator : ajuna-network

[Test]
        public void Ed25519SignatureTest()
        {
            var priKey0x =
                "0xf5e5767cf153319517630f226876b86c8160cc583bc013744c6bf255f5cc0ee5278117fc144c72340f67d0f2316e8386ceffbf2b2428c9c51fef7c597f1d426e";
            var pubKey0x = "0x278117fc144c72340f67d0f2316e8386ceffbf2b2428c9c51fef7c597f1d426e";

            var priKey = Utils.HexToByteArray(priKey0x);
            var pubKey = Utils.HexToByteArray(pubKey0x);

            var messageLength = _random.Next(10, 200);
            var message = new byte[messageLength];
            _random.NextBytes(message);

            //var message = signaturePayloadBytes.AsMemory().Slice(0, (int)payloadLength).ToArray();
            var simpleSign = Chaos.NaCl.Ed25519.Sign(message, priKey);

            replacedert.True(Chaos.NaCl.Ed25519.Verify(simpleSign, message, pubKey));
        }

19 View Source File : Wallet.cs
License : Apache License 2.0
Project Creator : ajuna-network

public async Task<bool> CreateAsync(string preplacedword, string mnemonic, string walletName = DefaultWalletName)
        {
            if (IsCreated)
            {
                Logger.Warn("Wallet already created.");
                return true;
            }

            if (!IsValidPreplacedword(preplacedword))
            {
                Logger.Warn(
                    "Preplacedword isn't is invalid, please provide a proper preplacedword. Minmimu eight size and must have upper, lower and digits.");
                return false;
            }

            Logger.Info("Creating new wallet from mnemonic.");

            var seed = Mnemonic.GetSecretKeyFromMnemonic(mnemonic, "Substrate", BIP39Wordlist.English);

            var randomBytes = new byte[48];

            _random.NextBytes(randomBytes);

            var memoryBytes = randomBytes.AsMemory();

            var pswBytes = Encoding.UTF8.GetBytes(preplacedword);

            var salt = memoryBytes.Slice(0, 16).ToArray();

            pswBytes = SHA256.Create().ComputeHash(pswBytes);

            var encryptedSeed =
                ManagedAes.EncryptStringToBytes_Aes(Utils.Bytes2HexString(seed, Utils.HexStringFormat.Pure), pswBytes, salt);

            var miniSecret = new MiniSecret(seed, ExpandMode.Ed25519);
            var getPair = miniSecret.GetPair();

            var keyType = KeyType.Sr25519;
            _walletFile = new WalletFile(keyType, getPair.Public.Key, encryptedSeed, salt);

            Caching.Persist(AddWalletFileType(walletName), _walletFile);

            Account = Account.Build(keyType, getPair.Secret.ToBytes(), getPair.Public.Key);

            if (IsOnline) _subscriptionAccountInfo = await SubscribeAccountInfoAsync();

            return true;
        }

19 View Source File : Wallet.cs
License : Apache License 2.0
Project Creator : ajuna-network

public async Task<bool> CreateAsync(string preplacedword, string walletName = DefaultWalletName)
        {
            if (IsCreated)
            {
                Logger.Warn("Wallet already created.");
                return true;
            }

            if (!IsValidPreplacedword(preplacedword))
            {
                Logger.Warn(
                    "Preplacedword isn't is invalid, please provide a proper preplacedword. Minmimu eight size and must have upper, lower and digits.");
                return false;
            }

            Logger.Info("Creating new wallet.");

            var randomBytes = new byte[48];

            _random.NextBytes(randomBytes);

            var memoryBytes = randomBytes.AsMemory();

            var pswBytes = Encoding.UTF8.GetBytes(preplacedword);

            var salt = memoryBytes.Slice(0, 16).ToArray();

            var seed = memoryBytes.Slice(16, 32).ToArray();

            pswBytes = SHA256.Create().ComputeHash(pswBytes);

            var encryptedSeed =
                ManagedAes.EncryptStringToBytes_Aes(Utils.Bytes2HexString(seed, Utils.HexStringFormat.Pure), pswBytes,
                    salt);

            Ed25519.KeyPairFromSeed(out var publicKey, out var privateKey, seed);

            var keyType = KeyType.Ed25519;
            _walletFile = new WalletFile(keyType, publicKey, encryptedSeed, salt);

            Caching.Persist(AddWalletFileType(walletName), _walletFile);

            Account = Account.Build(keyType, privateKey, publicKey);

            if (IsOnline) _subscriptionAccountInfo = await SubscribeAccountInfoAsync();

            return true;
        }

19 View Source File : InjectionBase.cs
License : MIT License
Project Creator : Akaion

internal void RandomiseDllHeaders()
        {
            // Write over the header region of the DLL with random bytes

            var randomBuffer = new byte[PeImage.Headers.PEHeader.SizeOfHeaders];

            new Random().NextBytes(randomBuffer);

            ProcessManager.Memory.ProtectBlock(DllBaseAddress, randomBuffer.Length, ProtectionType.ReadWrite);

            ProcessManager.Memory.WriteBlock(DllBaseAddress, randomBuffer);

            ProcessManager.Memory.ProtectBlock(DllBaseAddress, randomBuffer.Length, ProtectionType.ReadOnly);
        }

19 View Source File : EventStoreSnapshotStoreSpec.cs
License : Apache License 2.0
Project Creator : AkkaNetContrib

[Fact]
        public void SnapshotStore_should_save_bigger_size_snapshot()
        {
            var metadata = new SnapshotMetadata(Pid, 100L);
            var buffer = new byte[SnapshotByteSizeLimit];
            new Random().NextBytes(buffer);
            SnapshotStore.Tell(new SaveSnapshot(metadata, buffer), _senderProbe.Ref);
            _senderProbe.ExpectMsg<SaveSnapshotSuccess>(new TimeSpan?());
        }

19 View Source File : AesEncryptor.cs
License : MIT License
Project Creator : alexanderdna

public static byte[] Encrypt(byte[] plainTextBytes, byte[] keyBytes)
        {
            if (keyBytes.Length != KeySize) throw new ArgumentException("Invalid key length", nameof(keyBytes));

            byte[] initialVectorBytes = new byte[BlockSize];
            _rand.NextBytes(initialVectorBytes);

            byte[] cipherTextBytes = null;
            using (var symmetricKey = Rijndael.Create())
            {
                symmetricKey.Mode = CipherMode.CFB;
                symmetricKey.IV = initialVectorBytes;
                symmetricKey.Key = keyBytes;
                symmetricKey.Padding = PaddingMode.Zeros;
                symmetricKey.BlockSize = BlockSize * 8;
                symmetricKey.FeedbackSize = BlockSize * 8;
                using ICryptoTransform encryptor = symmetricKey.CreateEncryptor();
                using MemoryStream memStream = new MemoryStream();
                using (CryptoStream cryptoStream = new CryptoStream(memStream, encryptor, CryptoStreamMode.Write))
                {
                    cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
                }
                cipherTextBytes = memStream.ToArray();
            }

            byte[] returnBytes = new byte[initialVectorBytes.Length + cipherTextBytes.Length];
            Array.Copy(initialVectorBytes, returnBytes, initialVectorBytes.Length);
            Array.Copy(cipherTextBytes, 0, returnBytes, initialVectorBytes.Length, cipherTextBytes.Length);

            return returnBytes;
        }

19 View Source File : RandomExtensions.cs
License : MIT License
Project Creator : alexandre-spieser

public static long NextLong(this Random random, long min, long max)
        {
            if (max <= min)
                throw new ArgumentOutOfRangeException("max", "max must be > min!");

            //Working with ulong so that modulo works correctly with values > long.MaxValue
            ulong uRange = (ulong)(max - min);

            //Prevent a modulo bias; see https://stackoverflow.com/a/10984975/238419
            //for more information.
            //In the worst case, the expected number of calls is 2 (though usually it's
            //much closer to 1) so this loop doesn't really hurt performance at all.
            ulong ulongRand;
            do
            {
                byte[] buf = new byte[8];
                random.NextBytes(buf);
                ulongRand = (ulong)BitConverter.ToInt64(buf, 0);
            } while (ulongRand > ulong.MaxValue - ((ulong.MaxValue % uRange) + 1) % uRange);

            return (long)(ulongRand % uRange) + min;
        }

19 View Source File : PopcntBenchmark.cs
License : MIT License
Project Creator : alexandrnikitin

public ulong NextUInt64()
        {
            var buffer = new byte[sizeof(long)];
            random.NextBytes(buffer);
            return BitConverter.ToUInt64(buffer, 0);
        }

19 View Source File : BenchmarkHelper.cs
License : MIT License
Project Creator : alexis-

public static byte[] GenerateRandomData(int sizeMB)
    {
      Random rng = new Random();
      byte[] data = new byte[sizeMB * 1024 * 1024];

      rng.NextBytes(data);

      return data;
    }

19 View Source File : Utils.cs
License : MIT License
Project Creator : aliprogrammer69

public static string GetRandomHexNumber(int digits) {
            byte[] buffer = new byte[digits / 2];
            random.NextBytes(buffer);
            string result = String.Concat(buffer.Select(x => x.ToString("X2")).ToArray());
            if (digits % 2 == 0)
                return result;
            return result + random.Next(16).ToString("X");
        }

19 View Source File : TestUDT.cs
License : MIT License
Project Creator : allisterb

public static TestUDT MakeTestRecord(Random rng)
        {
            Guid _id = Guid.NewGuid();
            string _ids = _id.ToString("N");
            byte[] photo = new byte[4096];
            rng.NextBytes(photo);
            return new TestUDT()
            {
                ID = _id,
                FirstName = new Utf8Buffer("Gavial-" + _id.ToString("D").Substring(0, 4)),
                LastName = new Utf8Buffer("Buxarinovich-" + _id.ToString("D").Substring(0, 4)),
                DOB = _ids.StartsWith("7") ? (DateTime?)null : DateTime.UtcNow,
                Balance = 2131m,
                Photo = new FixedBuffer<byte>(photo)
            };
        }

19 View Source File : AuthenticationBase.cs
License : MIT License
Project Creator : andruzzzhka

internal static string CreateNonceValue ()
    {
      var src = new byte[16];
      var rand = new Random ();
      rand.NextBytes (src);

      var res = new StringBuilder (32);
      foreach (var b in src)
        res.Append (b.ToString ("x2"));

      return res.ToString ();
    }

19 View Source File : SmartHealthCardIncorrectSignatureJwsEncoder.cs
License : MIT License
Project Creator : angusmillar

public async Task<Result<string>> EncodeAsync<HeaderType, PayloadType>(HeaderType Header, PayloadType Payload)
    {
      Result<byte[]> HeaderSerializeResult = await HeaderSerializer.SerializeAsync(Header);
      Result<byte[]> PayloadSerializeResult = await PayloadSerializer.SerializeAsync(Payload);
      var CombineResult = Result.Combine(HeaderSerializeResult, PayloadSerializeResult);
      if (CombineResult.Failure)
        return Result<string>.Fail(CombineResult.ErrorMessage);

      var HeaderSegment = Base64UrlEncoder.Encode(HeaderSerializeResult.Value);
      var PayloadSegment = Base64UrlEncoder.Encode(PayloadSerializeResult.Value);

      var BytesToSign = Utf8EncodingSupport.GetBytes($"{HeaderSegment}.{PayloadSegment}");

      Result<byte[]> SignatureResult = Algorithm.Sign(BytesToSign);

      Random Random = new Random();
      Byte[] WickedBytes = new Byte[SignatureResult.Value.Length];
      Random.NextBytes(WickedBytes);
     
      if (SignatureResult.Failure)
        return Result<string>.Fail(SignatureResult.ErrorMessage);
       
      var SignatureSegment = Base64UrlEncoder.Encode(WickedBytes);

      return Result<string>.Ok($"{HeaderSegment}.{PayloadSegment}.{ SignatureSegment}");
    }

19 View Source File : RandomHelper.cs
License : MIT License
Project Creator : AnotherEnd15

public static ulong RandUInt64(this Random random)
        {
            byte[] byte8 = new byte[8];
            random.NextBytes(byte8);
            return BitConverter.ToUInt64(byte8, 0);
        }

19 View Source File : RandomHelper.cs
License : MIT License
Project Creator : AnotherEnd15

public static long RandInt64(this Random random)
        {
            byte[] byte8 = new byte[8];
            random.NextBytes(byte8);
            return BitConverter.ToInt64(byte8, 0);
        }

19 View Source File : Mathf.cs
License : MIT License
Project Creator : AnotherEnd15

internal static long RandomToLong(System.Random r)
        {
            byte[] buffer = new byte[8];
            r.NextBytes(buffer);
            return (long) BitConverter.ToUInt64(buffer, 0) & long.MaxValue;
        }

19 View Source File : RandomHelper.cs
License : MIT License
Project Creator : AnotherEnd15

public static ulong RandUInt64()
        {
            byte[] byte8 = new byte[8];
            random.NextBytes(byte8);
            return BitConverter.ToUInt64(byte8, 0);
        }

19 View Source File : RandomHelper.cs
License : MIT License
Project Creator : AnotherEnd15

public static long RandInt64()
        {
            byte[] byte8 = new byte[8];
            random.NextBytes(byte8);
            return BitConverter.ToInt64(byte8, 0);
        }

19 View Source File : DistributedLockProvider.cs
License : MIT License
Project Creator : ansel86castro

private string GetToken()
        {
            lock (_rand)
            {
                byte[] bytes = new byte[32];
                _rand.NextBytes(bytes);

                StringBuilder sb = new StringBuilder(Environment.MachineName);
                sb.Append(":");

                for (int i = 0; i < bytes.Length; i++)
                {
                    sb.Append(bytes[i].ToString("x2"));
                }
                return sb.ToString();               
            }
        }

See More Examples