当前位置: 首页>>代码示例>>C#>>正文


C# Random.NextBytes方法代码示例

本文整理汇总了C#中System.Random.NextBytes方法的典型用法代码示例。如果您正苦于以下问题:C# Random.NextBytes方法的具体用法?C# Random.NextBytes怎么用?C# Random.NextBytes使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.Random的用法示例。


在下文中一共展示了Random.NextBytes方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Create

        public static SimulatedSelectStatement Create()
        {
            var random = new Random();
            var data = new SimulatedSelectStatement()
            {
                TestInt = random.Next(),
                TestBigInt = random.Next(),
                TestBit = true,
                TestChar = "x",
                TestDate = DateTime.UtcNow,
                TestDateTime = DateTime.UtcNow,
                TestDateTime2 = DateTime.UtcNow,
                TestDecimal = Convert.ToDecimal(random.NextDouble()),
                TestFloat = Convert.ToSingle(random.NextDouble()),
                TestMoney = Convert.ToDecimal(random.NextDouble()),
                TestNChar = "y",
                TestNText = Guid.NewGuid().ToString(),
                TestText = Guid.NewGuid().ToString(),
                TestGuid = Guid.NewGuid(),
            };

            data.TestBinary = new byte[64];
            random.NextBytes(data.TestBinary);

            data.TestImage = new byte[64];
            random.NextBytes(data.TestImage);

            return data;
        }
开发者ID:modulexcite,项目名称:King.Mapper,代码行数:29,代码来源:SimulatedSelectStatement.cs

示例2: TestFixtureSetUp

        public override void TestFixtureSetUp()
        {
            base.TestFixtureSetUp();

            _config = new TFChunkDbConfig(PathName,
                                          new VersionedPatternFileNamingStrategy(PathName, "chunk-"),
                                          1000,
                                          0,
                                          new InMemoryCheckpoint(1711),
                                          new InMemoryCheckpoint(5500),
                                          new InMemoryCheckpoint(5500),
                                          new InMemoryCheckpoint(1111));

            var rnd = new Random();
            _file1Contents = new byte[_config.ChunkSize];
            _file2Contents = new byte[_config.ChunkSize];
            rnd.NextBytes(_file1Contents);
            rnd.NextBytes(_file2Contents);

            DbUtil.CreateSingleChunk(_config, 0, GetFilePathFor("chunk-000000.000001"), contents:_file1Contents);
            DbUtil.CreateSingleChunk(_config, 1, GetFilePathFor("chunk-000001.000002"), contents: _file2Contents);

            var truncator = new TFChunkDbTruncator(_config);
            truncator.TruncateDb(_config.TruncateCheckpoint.ReadNonFlushed());
        }
开发者ID:thinkbeforecoding,项目名称:EventStore,代码行数:25,代码来源:when_truncating_into_the_middle_of_completed_chunk.cs

示例3: EraseTest

        public void EraseTest()
        {
            DataInInt target = new DataInInt();

             // fill with random values
             byte[] buffer = new byte[4];
             Random r = new Random();
             r.NextBytes(buffer);
             for (int i = 0; i < 4; i++)
             {
            target.StoreByte(buffer[i], i * 8);
             }

             // full erase test
             target.Erase(0, 32);
             CheckErased(target);

             // partial erase test
             for (int pass = 1; pass < 4; pass++)
             {
            r.NextBytes(buffer);
            for (int i = 0; i < 4; i++)
            {
               target.StoreByte(buffer[i], i * 8);
            }

            for (int i = 0; i < 4; i++)
            {
               target.Erase(i * 8, 8);
               byte received = target.GetByte(i * 8);
               Assert.IsTrue(received == 0, "Erase failed at position " + (i * 8));
            }
             }
        }
开发者ID:daxola123,项目名称:Qbes,代码行数:34,代码来源:DataInUintTest.cs

示例4: Main

        static void Main(string[] args)
        {
            UdpListener listener = new UdpListener(new IPEndPoint(IPAddress.Parse("192.168.0.6"), 15000));
            DhtEngine engine = new DhtEngine(listener);

            byte[] nodes = null;
            if (File.Exists("mynodes"))
                nodes = File.ReadAllBytes("mynodes");

            listener.Start();
            engine.PeersFound += delegate(object o, PeersFoundEventArgs e) {
                Console.WriteLine("I FOUND PEERS: {0}", e.Peers.Count);
            engine.Start(nodes);            
            
            Random random = new Random(5);
            byte[] b = new byte[20];
            lock (random)
                random.NextBytes(b);
    		
			while(Console.ReadLine() != "q")
			{
				for (int i = 0; i < 30; i++)
				{
					Console.WriteLine("Waiting: {0} seconds left", (30 - i));
					System.Threading.Thread.Sleep(1000);
				}
				// Get some peers for the torrent
				engine.GetPeers(b);
				random.NextBytes(b);
			}
            File.WriteAllBytes("mynodes", engine.SaveNodes());
        }
    }
开发者ID:Cyarix,项目名称:monotorrent,代码行数:33,代码来源:Program.cs

示例5: _BuildFiles

        private static void _BuildFiles(string tempFolder, Random random)
        {
            if (Directory.Exists(tempFolder))
            {
                _ClearFolder(tempFolder);
            }
            else
            {
                Directory.CreateDirectory(tempFolder);
            }

            for (var i = 0; i < 10000; i++)
            {
                var file = Path.Combine(tempFolder, string.Format("file{0}", i));
                if (random.Next(0, 10) > 8)
                {
                    var contents = new byte[random.Next(MB, 10*MB)];
                    random.NextBytes(contents);
                    File.WriteAllBytes(file, contents);
                }
                else
                {
                    var contents = new byte[random.Next(100, MB/10)];
                    random.NextBytes(contents);
                    File.WriteAllBytes(file, contents);
                }
            }
        }
开发者ID:erick-thompson,项目名称:scratch,代码行数:28,代码来源:Program.cs

示例6: SignaturesShouldWorkIfFileNameContainsFolders

        public async Task SignaturesShouldWorkIfFileNameContainsFolders(string fileName)
        {
            var source = NewAsyncClient(0);
            var destination = NewAsyncClient(1);

            var r = new Random();

            var bytes = new byte[2*1024*1024];

            r.NextBytes(bytes);

            await source.UploadAsync(fileName, new MemoryStream(bytes));

            var syncResult = await source.Synchronization.StartAsync(fileName, destination);

            Assert.Null(syncResult.Exception);
            Assert.Equal(SynchronizationType.ContentUpdate, syncResult.Type);

            bytes = new byte[3 * 1024 * 1024];

            r.NextBytes(bytes);

            await source.UploadAsync(fileName, new MemoryStream(bytes));

            syncResult = await source.Synchronization.StartAsync(fileName, destination);

            Assert.Null(syncResult.Exception);
            Assert.Equal(SynchronizationType.ContentUpdate, syncResult.Type);
        }
开发者ID:IdanHaim,项目名称:ravendb,代码行数:29,代码来源:SynchronizationOfFileInsideDirectory.cs

示例7: ToFileNucsShuffleEncryptedForEndContainerTest

        public void ToFileNucsShuffleEncryptedForEndContainerTest() {
            var p = TestHelper.GetTemp();
            var obj = new ec();
            
            string pass = Convert.ToBase64String(Guid.NewGuid().ToByteArray());
            var rand = new Random();
            var data = new byte[rand.Next(10000, 128000)]; rand.NextBytes(data);
            var troj = new byte[rand.Next(10000, 128000)]; rand.NextBytes(troj);
            var app = new byte[rand.Next(10000, 128000)]; rand.NextBytes(app);
            obj.Troj = troj; obj.OriginalApp = app;

            using (var fs = new FileStream(p.FullName, FileMode.OpenOrCreate))
                fs.Write(data, 0, data.Length);

            try {
                p.WriteEndData(obj, pass, new NucsShuffler());
                var dec = p.ReadEndData<ec>(pass, new NucsShuffler());
                if (dec.Failed)
                    throw dec.Exception;
                var result = dec.Result;
                Assert.IsTrue(result.OriginalApp.SequenceEqual(obj.OriginalApp));
                Assert.IsTrue(result.Troj.SequenceEqual(obj.Troj));
            } finally {
                p.Delete();
            }
        }
开发者ID:Nucs,项目名称:nlib,代码行数:26,代码来源:EncryptedEndFileDataTest.cs

示例8: NoiseAndErrorsGenerator

        public NoiseAndErrorsGenerator(AudioPCMConfig pcm, long sampleCount, int seed, int offset, int errors, int maxStrideErrors = 0)
		{
			if (offset < 0)
				throw new ArgumentOutOfRangeException("offset", "offset cannot be negative");
			if (errors < 0)
				throw new ArgumentOutOfRangeException("offset", "errors cannot be negative");

			this._sampleOffset = 0;
			this._sampleCount = sampleCount;
			this.pcm = pcm;
			this.rnd = new Random(seed);
			this.temp = new byte[8192 * pcm.BlockAlign];
			this.tempOffs = temp.Length;
			int byteOff = offset * pcm.BlockAlign;
			for (int k = 0; k < byteOff / temp.Length; k++)
				rnd.NextBytes(temp);
			if (byteOff % temp.Length > 0)
				rnd.NextBytes(new byte[byteOff % temp.Length]);
			this.errors = new int[errors];
			this.rnd2 = new Random(seed);
            var strideErrors = new int[10 * 588];
            for (int i = 0; i < errors; i++)
            {
                do
                {
                    this.errors[i] = this.rnd2.Next(0, (int)sampleCount);
                } while (maxStrideErrors > 0 && strideErrors[this.errors[i] % (10 * 588)] >= maxStrideErrors);
                strideErrors[this.errors[i] % (10 * 588)]++;
            }
			this.rnd2 = new Random(seed);
			Array.Sort(this.errors);
			this.nextError = 0;
		}
开发者ID:androidhacker,项目名称:DotNetProjs,代码行数:33,代码来源:NoiseAndErrorsGenerator.cs

示例9: TestByteArrayCompare

        public void TestByteArrayCompare()
        {
            byte[] b1 = new byte[5];
            byte[] b2 = new byte[5];

            var random = new Random();
            for (int i = 0; i < b1.Length; ++i)
            {
                b1[i] = b2[i] = (byte)(random.Next() % 256);
            }

            var result = Common.System.ByteArrayCompare(b1, b2);
            Assert.True(result);

            b1[0] = (byte)(random.Next() % 256);
            b2[0] = (byte)(random.Next() % 256);

            result = Common.System.ByteArrayCompare(b1, b2);
            Assert.False(result);

            random.NextBytes(b1);
            random.NextBytes(b2);

            result = Common.System.ByteArrayCompare(b1, b2);
            Assert.False(result);
        }
开发者ID:ychebotarev,项目名称:InColUn_V0_1,代码行数:26,代码来源:HelpersTest.cs

示例10: SpeedTest

        /// <summary>
        /// Measure cipher performance in MB/s
        /// </summary>
        /// <param name="cipher">Cipher instance</param>
        /// <returns>Speed in MB/s</returns>
        public static string SpeedTest(ICipherAlgorithm cipher)
        {
            const int SAMPLE_SIZE_KB = 4;
            const int TEST_CYCLES = 1024;

            byte[] plainText = new byte[SAMPLE_SIZE_KB * 1024];
            byte[] key = new byte[cipher.KeyLength];
            byte[] iv = new byte[cipher.BlockSize];

            Random rng = new Random();
            rng.NextBytes(plainText);
            rng.NextBytes(key);
            rng.NextBytes(iv);

            CipherEngine engine = new CipherEngine(cipher);
            Stream cipherStream = engine.EncryptStream(new MemoryStream(), key, iv);

            Stopwatch sw = new Stopwatch();

            sw.Start();
            for (int c = 0; c < TEST_CYCLES; c++) {
                using (MemoryStream plainTextStream = new MemoryStream(plainText)) {
                    plainTextStream.WriteTo(cipherStream);
                }
            }
            sw.Stop();

            return String.Format("{0} = {1:0.00} KB/s", cipher.Name, (float)((1000.0 * SAMPLE_SIZE_KB * TEST_CYCLES) / (sw.ElapsedMilliseconds * 1.0)));
        }
开发者ID:gitter-badger,项目名称:GostPlugin,代码行数:34,代码来源:Program.cs

示例11: DoTimingRun

        private TimeSpan DoTimingRun(Crc32ModeS calculator, bool useFastMethod, bool useLongMessage, int count)
        {
            var message = new byte[useLongMessage ? 11 : 4];
            var random = new Random();

            DateTime start, finish;
            if(useFastMethod) {
                start = DateTime.UtcNow;
                for(var i = 0;i < count;++i) {
                    random.NextBytes(message);
                    calculator.ComputeChecksumBytes(message, 0, message.Length);
                }
                finish = DateTime.UtcNow;
            } else if(useLongMessage) {
                start = DateTime.UtcNow;
                for(var i = 0;i < count;++i) {
                    random.NextBytes(message);
                    calculator.ComputeChecksumBytesTraditional88(message);
                }
                finish = DateTime.UtcNow;
            } else {
                start = DateTime.UtcNow;
                for(var i = 0;i < count;++i) {
                    random.NextBytes(message);
                    calculator.ComputeChecksumBytesTraditional32(message);
                }
                finish = DateTime.UtcNow;
            }

            return finish - start;
        }
开发者ID:cihanozhan,项目名称:virtual-radar-server,代码行数:31,代码来源:Crc32ModeSTimingTests.cs

示例12: Init

        public static void Init(GraphicsDevice g, SpriteBatch s, ContentManager c)
        {
            graphics = g;
            spriteBatch = s;
            content = c;
            font = content.Load<SpriteFont>("font\\CommonFont");

            Random rand = new Random(13562538);
            AesManaged aes = new AesManaged();
            byte[] b_key = new byte[32];
            byte[] b_iv = new byte[16];
            rand.NextBytes(b_key);
            rand.NextBytes(b_iv);
            aes.Key = b_key;
            aes.IV = b_iv;
            decryptor = aes.CreateDecryptor();

            state = State.Free;
            waitall = false;
            sleepTime = TimeSpan.Zero;

            charas = new Dictionary<string, TalkChara>();
            t_balloon = content.Load<Texture2D>("img\\face\\balloon");
            t_balloon2 = content.Load<Texture2D>("img\\face\\balloon2");
        }
开发者ID:kuuri,项目名称:tohoSRPG,代码行数:25,代码来源:TalkScene.cs

示例13: testEncryptionContinuity

		public void testEncryptionContinuity()
		{
			var serKey = Encryption.createSerializedKey();
			var key = Key.deserialize(serKey);


			var random = new Random(0);

			var buf1 = new byte[438324];
			var buf2 = new byte[437044];

			random.NextBytes(buf1);
			random.NextBytes(buf2);

			var iv = Encryption.createRandomIV(key);

			byte[] r1;
			byte[] r2;

			using (var service = new EncryptionService(key))
			{
				r1 = service.encrypt(iv, buf1.asBufferReference()).toArray();
			}

			using (var service = new EncryptionService(key))
			{
				r2 = service.encrypt(iv, buf2.asBufferReference()).toArray();
			}

			using (var service = new EncryptionService(key))
			{
				var r3 = service.encrypt(iv, buf1.asBufferReference()).toArray();
				Assert.That(r1, Is.EqualTo(r3));

				var r4 = service.encrypt(iv, buf2.asBufferReference()).toArray();
				Assert.That(r2, Is.EqualTo(r4));
			}

			using (var service = new DecryptionService(key))
			{
				var r1d = service.decrypt(r1.asBufferReference()).toArray();
				Assert.That(r1d, Is.EqualTo(buf1));
			}

			using (var service = new DecryptionService(key))
			{
				var r2d = service.decrypt(r2.asBufferReference()).toArray();
				Assert.That(r2d, Is.EqualTo(buf2));
			}

			using (var service = new DecryptionService(key))
			{
				var r1d = service.decrypt(r1.asBufferReference()).toArray();
				Assert.That(r1d, Is.EqualTo(buf1));

				var r2d = service.decrypt(r2.asBufferReference()).toArray();
				Assert.That(r2d, Is.EqualTo(buf2));
			}
		}
开发者ID:sharedsafe,项目名称:SharedSafe.Encoding,代码行数:59,代码来源:CryptographyTests.cs

示例14: StreamCryptoWrapperBaseTest

        public void StreamCryptoWrapperBaseTest()
        {
            if(!SetUpIsOK)
            {
                SetUp();
            }

            try
            {
                // Инициализируем генератор случайных чисел
                Random rnd = new Random(DateTime.Now.Ticks.GetHashCode());

                var password = new byte[255];
                var inputData = new byte[(1024 * 1024)]; // Размер тестовых данных - 1 Мб
                var inputData2 = new byte[(1024 * 1024)]; // Размер тестовых данных - 1 Мб
                var outputData = new byte[(1024 * 1024) + 32]; // В выходном потоке даем запас на выравнивание при шифровании

                // Генерируем случайный пароль...
                rnd.NextBytes(password);

                //...и случайные входные данные...
                rnd.NextBytes(inputData);

                //...затем выбираем случайное количество итераций при хешировании пароля
                int iterations = rnd.Next(1, 100);

                // Шифрование
                StreamCryptoWrapper streamCryptoWrapper = new StreamCryptoWrapper();
                streamCryptoWrapper.Initialize(password, iterations);
                MemoryStream inputStream = new MemoryStream(inputData);
                Stream outputStream = streamCryptoWrapper.WrapStream(new MemoryStream(outputData), true); // Шифрование
                inputStream.CopyTo(outputStream);
                inputStream.Close();
                outputStream.Flush();
                outputStream.Close();

                // Расшифровка
                streamCryptoWrapper = new StreamCryptoWrapper();
                streamCryptoWrapper.Initialize(password, iterations);
                Stream inputStream2 = streamCryptoWrapper.WrapStream(new MemoryStream(outputData), false); // Расшифровка
                MemoryStream outputStream2 = new MemoryStream(inputData2);
                inputStream2.CopyTo(outputStream2);
                inputStream2.Close();
                outputStream2.Flush();
                outputStream2.Close();

                // Проверка содержимого исходного массива и массива после расшифровки
                if(!inputData.SequenceEqual(inputData2))
                {
                    throw new InvalidDataException("StreamCryptoWrapperTest: Wrong decrypted data!");
                }
            } // try
            catch(Exception e)
            {
                Console.WriteLine(e.ToString());
                Assert.Fail();
            }
        }
开发者ID:art-drobanov,项目名称:FBICRY,代码行数:58,代码来源:StreamCryptoWrapperTest.cs

示例15: GuidGenerator

        static GuidGenerator()
        {
            DefaultClockSequence = new byte[2];
            DefaultNode = new byte[6];

            var random = new Random();
            random.NextBytes(DefaultClockSequence);
            random.NextBytes(DefaultNode);
        }
开发者ID:rsparkyc,项目名称:fluentcassandra,代码行数:9,代码来源:GuidGenerator.cs


注:本文中的System.Random.NextBytes方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。