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


C# Random.NextBytes方法代码示例

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


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

示例1: CreateFileToSend

        private string CreateFileToSend(int size, bool sendPreAndPostBuffers, out byte[] preBuffer, out byte[] postBuffer, out Fletcher32 checksum)
        {
            // Create file to send
            var random = new Random();
            int fileSize = sendPreAndPostBuffers ? size - 512 : size;

            checksum = new Fletcher32();

            preBuffer = null;
            if (sendPreAndPostBuffers)
            {
                preBuffer = new byte[256];
                random.NextBytes(preBuffer);
                checksum.Add(preBuffer, 0, preBuffer.Length);
            }

            byte[] fileBuffer = new byte[fileSize];
            random.NextBytes(fileBuffer);

            string path = Path.GetTempFileName();
            File.WriteAllBytes(path, fileBuffer);

            checksum.Add(fileBuffer, 0, fileBuffer.Length);

            postBuffer = null;
            if (sendPreAndPostBuffers)
            {
                postBuffer = new byte[256];
                random.NextBytes(postBuffer);
                checksum.Add(postBuffer, 0, postBuffer.Length);
            }

            return path;
        }
开发者ID:chcosta,项目名称:corefx,代码行数:34,代码来源:SendFile.cs

示例2: TestAlgorithms

	public static bool TestAlgorithms(SymmetricAlgorithm encAlgorithm, SymmetricAlgorithm decAlgorithm, CipherMode[] modes, int maxLength, int iterations)
	{
		Random rand = new Random();
		
		for (int i = 0; i < iterations; i++)
		{
			// Create random data, key, IV, mode
			//
			byte[] key = new byte[KeySizeBytes[rand.Next(KeySizeBytes.Length)]];
			rand.NextBytes(key);
			
			byte[] data = new byte[rand.Next(1, maxLength + 1)];
			rand.NextBytes(data);

			byte[] IV = new byte[BlockSizeBytes];
			rand.NextBytes(IV);
			
			CipherMode mode = modes[rand.Next(modes.Length)];
			PaddingMode padding = PaddingModes[new Random().Next(PaddingModes.Length)];

			// Encrypt the data
			//
			byte[] encryptedData;
			encAlgorithm.Key = key;
			encAlgorithm.IV = IV;
			encAlgorithm.Mode = mode;
			encAlgorithm.Padding = padding;

			ICryptoTransform transform = encAlgorithm.CreateEncryptor();
			encryptedData = transform.TransformFinalBlock(data, 0, data.Length);

			// Decrypt the data
			//
			byte[] decryptedData;
			decAlgorithm.Key = key;
			decAlgorithm.IV = IV;
			decAlgorithm.Mode = mode;
			decAlgorithm.Padding = padding;

			transform = decAlgorithm.CreateDecryptor();
			decryptedData = transform.TransformFinalBlock(encryptedData, 0, encryptedData.Length);

			if (!CompareBytes(data, decryptedData))
			{
				Console.WriteLine("ERROR - roundtrip encrypt/decrypt failed!\n");
				Console.WriteLine("Encryption algorithm: {0}", encAlgorithm.ToString());
				Console.WriteLine("Decryption algorithm: {0}", decAlgorithm.ToString());
				Console.WriteLine("Original data: {0}", ByteArrayToString(data));
				Console.WriteLine("Roundtrip data: {0}", ByteArrayToString(decryptedData));
				Console.WriteLine("Key: {0}", ByteArrayToString(key));
				Console.WriteLine("IV: {0}", ByteArrayToString(IV));
				Console.WriteLine("Cipher mode: {0}", mode.ToString());
				Console.WriteLine("Padding mode: {0}", padding.ToString());
				return false;
			}
		}

		return true;
	}
开发者ID:koson,项目名称:.NETMF_for_LPC17xx,代码行数:59,代码来源:AESInterop.cs

示例3: Execute

        public static void Execute()
        {
            Console.WriteLine("Executing Pair test");

            _clientData = new byte[DataSize];
            _serverData = new byte[DataSize];
            var r = new Random();
            r.NextBytes(_clientData);
            r.NextBytes(_serverData);

            var clientThread = new Thread(
                () =>
                {
                    var req = new PairSocket();
                    req.Connect(InprocAddress);

                    byte[] streamOutput = new byte[BufferSize];
                    while (true)
                    {
                        var sw = Stopwatch.StartNew();
                        for (int i = 0; i < Iter; i++)
                        {
                            var result = req.SendImmediate(_clientData);
                            Trace.Assert(result);
                            int read = 0;
                            using (var stream = req.ReceiveStream())
                                while (stream.Length != stream.Position)
                                    read += stream.Read(streamOutput, 0, streamOutput.Length);
                            Trace.Assert(read == _serverData.Length);
                        }
                        sw.Stop();
                        var secondsPerSend = sw.Elapsed.TotalSeconds / (double)Iter;
                        Console.WriteLine("Pair Time {0} us, {1} per second, {2} mb/s ",
                            (int)(secondsPerSend * 1000d * 1000d),
                            (int)(1d / secondsPerSend),
                            (int)(DataSize * 2d / (1024d * 1024d * secondsPerSend)));
                    }
                });
            clientThread.Start();

            {
                var rep = new PairSocket();
                rep.Bind(InprocAddress);

                byte[] streamOutput = new byte[BufferSize];

                var sw = Stopwatch.StartNew();
                while (sw.Elapsed.TotalSeconds < 10)
                {
                    int read = 0;
                    using (var stream = rep.ReceiveStream())
                        while (stream.Length != stream.Position)
                            read += stream.Read(streamOutput, 0, streamOutput.Length);
                    rep.SendImmediate(_serverData);
                }

                clientThread.Abort();
            }
        }
开发者ID:gitter-badger,项目名称:NNanomsg,代码行数:59,代码来源:Test_Pair.cs

示例4: SingleInstanceHandler

    /// <summary>
    /// Constructs a handler for an application to consolidate arguments from multiple instances
    /// (within a Timeout period) into a single instance.
    /// </summary>
    /// <param name="uniqueID">A unique string for the application.</param>
    public SingleInstanceHandler(string uniqueID)
    {
        var rng = new Random(uniqueID.GetHashCode());
        byte[] ipcMutexGuidBytes = new byte[16];
        byte[] ipcNamedPipeGuidBytes = new byte[16];
        rng.NextBytes(ipcMutexGuidBytes);
        rng.NextBytes(ipcNamedPipeGuidBytes);
        ipcMutexGuid = new Guid(ipcMutexGuidBytes).ToString().Trim('{', '}');
        ipcNamedPipeGuid = new Guid(ipcNamedPipeGuidBytes).ToString().Trim('{', '}');

        Timeout = 500;
    }
开发者ID:lgatto,项目名称:proteowizard,代码行数:17,代码来源:SingleInstanceHandler.cs

示例5: CreateT

 protected string CreateT(HashSet<string> set, int seed)
 {
     int stringLength = seed % 10 + 5;
     Random rand = new Random(seed);
     byte[] bytes = new byte[stringLength];
     rand.NextBytes(bytes);
     string ret = Convert.ToBase64String(bytes);
     while (set.Contains(ret))
     {
         rand.NextBytes(bytes);
         ret = Convert.ToBase64String(bytes);
     }
     return ret;
 }
开发者ID:Corillian,项目名称:corefx,代码行数:14,代码来源:HashSet.Generic.Tests.AsNonGenericIEnumerable.cs

示例6: Test

	public static bool Test()
	{
		Random rnd = new Random();
		
		// create a random array of random bytes
		int len = rnd.Next(1000000);
		byte[] plain = new byte[len];
		rnd.NextBytes(plain);
		Console.Write("Working with " + len + " bytes of plaintext...");

		// encrypt with salt
		RC2CryptoServiceProvider rc2s = new RC2CryptoServiceProvider();
		rc2s.UseSalt = true;
		rc2s.Key = new byte[]{1,2,3,4,5};
		byte[] encrypted = (rc2s.CreateEncryptor()).TransformFinalBlock(plain, 0, plain.Length);

		// decrypt with salt
		RC2CryptoServiceProvider rc2sd = new RC2CryptoServiceProvider();
		rc2sd.UseSalt = true;
		rc2sd.Key = rc2s.Key;
		rc2sd.IV = rc2s.IV;
		byte[] decrypted = (rc2sd.CreateDecryptor()).TransformFinalBlock(encrypted, 0, encrypted.Length);
		
		if (CompareSlow(plain, decrypted))
		{
			Console.WriteLine("OK.");
			return true;
		} else {
			Console.WriteLine("FAIL.");
			return false;
		}
	}
开发者ID:koson,项目名称:.NETMF_for_LPC17xx,代码行数:32,代码来源:RC2Salt3.cs

示例7: Page_Load

	protected void Page_Load(object sender, EventArgs e)
	{
		Random rnd = new Random();
		byte[] buffer = new byte[1050];
		rnd.NextBytes(buffer);
		ViewState["Data"] = buffer;
	}
开发者ID:Helen1987,项目名称:edu,代码行数:7,代码来源:ViewStateChunking.aspx.cs

示例8: VirtualNetworkStream_SingleThreadIntegrityTest_Ok

        public void VirtualNetworkStream_SingleThreadIntegrityTest_Ok()
        {
            var rnd = new Random();
            var network = new VirtualNetwork();

            using (var client = new VirtualNetworkStream(network, isServer: false))
            using (var server = new VirtualNetworkStream(network, isServer: true))
            {
                for (int i = 0; i < 100000; i++)
                {
                    int bufferSize = rnd.Next(1, 2048);

                    byte[] writeFrame = new byte[bufferSize];
                    rnd.NextBytes(writeFrame);
                    uint writeChecksum = Fletcher32.Checksum(writeFrame, 0, writeFrame.Length);
                    client.Write(writeFrame, 0, writeFrame.Length);

                    var readFrame = new byte[writeFrame.Length];
                    server.Read(readFrame, 0, readFrame.Length);
                    uint readChecksum = Fletcher32.Checksum(readFrame, 0, readFrame.Length);

                    Assert.Equal(writeChecksum, readChecksum);
                }
            }
        }
开发者ID:nbilling,项目名称:corefx,代码行数:25,代码来源:VirtualNetworkStreamTest.cs

示例9: Test

	public static bool Test()
	{
		Random rnd = new Random();
		
		// create a random array of random bytes
		int len = rnd.Next(1000000);
		byte[] plain = new byte[len];
		rnd.NextBytes(plain);
		Console.Write("Working with " + len + " bytes of plaintext...");

		// encrypt by default
		RC2CryptoServiceProvider rc2 = new RC2CryptoServiceProvider();
		rc2.Key = new byte[]{5,4,3,2,1,0,0,0,0,0,0,0,0,0,0,0};	// salt only takes effect when we use a 40-bit key
		byte[] encrypted1 = (rc2.CreateEncryptor()).TransformFinalBlock(plain, 0, plain.Length);

		// encrypt with salt
		RC2CryptoServiceProvider rc2s = new RC2CryptoServiceProvider();
		rc2s.UseSalt = true;
		rc2s.Key = new byte[]{1,2,3,4,5};
		rc2s.IV = rc2.IV;
		byte[] encrypted2 = (rc2s.CreateEncryptor()).TransformFinalBlock(plain, 0, plain.Length);

		if (CompareSlow(encrypted1, encrypted2))
		{
			Console.WriteLine("OK.");
			return true;
		} else {
			Console.WriteLine("FAIL.");
			return false;
		}
	}
开发者ID:koson,项目名称:.NETMF_for_LPC17xx,代码行数:31,代码来源:RC2Salt2.cs

示例10: AsyncReadWriteChain_ReadWrite_APM

        public async Task AsyncReadWriteChain_ReadWrite_APM(int iterations, int writeBufferSize, int readBufferSize, bool cancelableToken)
        {
            var writeBuffer = new byte[writeBufferSize];
            var readBuffer = new byte[readBufferSize];
            var rand = new Random();
            var cancellationToken = cancelableToken ? new CancellationTokenSource().Token : CancellationToken.None;

            using (ServerClientPair pair = CreateServerClientPair())
            {
                // Repeatedly and asynchronously write to the writable pipe and read from the readable pipe,
                // verifying that the correct data made it through.
                for (int iter = 0; iter < iterations; iter++)
                {
                    rand.NextBytes(writeBuffer);
                    Task write = Task.Factory.FromAsync<byte[], int, int>(pair.writeablePipe.BeginWrite, pair.writeablePipe.EndWrite, writeBuffer, 0, writeBuffer.Length, null);

                    int totalRead = 0;
                    while (totalRead < writeBuffer.Length)
                    {
                        Task<int> read = Task.Factory.FromAsync<byte[], int, int, int>(pair.readablePipe.BeginRead, pair.readablePipe.EndRead, readBuffer, 0, readBuffer.Length, null);
                        int numRead = await read;
                        Assert.True(numRead > 0);
                        Assert.Equal<byte>(
                            new ArraySegment<byte>(writeBuffer, totalRead, numRead),
                            new ArraySegment<byte>(readBuffer, 0, numRead));
                        totalRead += numRead;
                    }
                    Assert.Equal(writeBuffer.Length, totalRead);

                    await write;
                }
            }
        }
开发者ID:dotnet,项目名称:corefx,代码行数:33,代码来源:PipeTest.Read.netstandard17.cs

示例11: VirtualNetwork_MultiThreadIntegrityTest_Ok

        public void VirtualNetwork_MultiThreadIntegrityTest_Ok()
        {
            var rnd = new Random();

            var network = new VirtualNetwork();
            var checksums = new ConcurrentDictionary<int, uint>();

            Parallel.For(0, 100000, async (int i) =>
            {
                int bufferSize = rnd.Next(5, 2048);

                byte[] writeFrame = new byte[bufferSize];
                rnd.NextBytes(writeFrame);
                
                // First 4 bytes represent the sequence number.
                byte [] sequenceNo = BitConverter.GetBytes(i);
                sequenceNo.CopyTo(writeFrame, 0);

                uint writeChecksum = Fletcher32.Checksum(writeFrame, 0, writeFrame.Length);
                checksums.AddOrUpdate(i, writeChecksum, (seq, checkSum) => { Debug.Fail("Attempt to update checksum."); return 0; });

                network.WriteFrame(i % 2 == 0, writeFrame);

                int delayMilliseconds = rnd.Next(0, 1000);
                await Task.Delay(delayMilliseconds);

                byte[] readFrame;
                network.ReadFrame(i % 2 == 1, out readFrame);

                uint readChecksum = Fletcher32.Checksum(readFrame, 0, readFrame.Length);

                int idx = BitConverter.ToInt32(readFrame, 0);
                Assert.Equal(checksums[idx], readChecksum);
            });
        }
开发者ID:ESgarbi,项目名称:corefx,代码行数:35,代码来源:VirtualNetworkTest.cs

示例12: Main

 public static void Main()
 {
     Debug.Print("BLE Shield");
     var port = SerialPorts.COM1; // using D0 & D1
     //var port = SerialPorts.COM2; // using D2 & D3
     var bleShield = new SerialPort(port, 19200, Parity.None, 8, StopBits.None);
     bleShield.DataReceived += (sender, args) =>
     {
         var receiveBuffer = new byte[16];
         int bytesReceived = bleShield.Read(receiveBuffer, 0, receiveBuffer.Length);
         if (bytesReceived > 0)
         {
             Debug.Print("Bytes received: " + bytesReceived);
             Debug.Print(new String(Encoding.UTF8.GetChars(receiveBuffer)));
         }
     };
     bleShield.Open();
     while (true)
     {
         var random = new Random();
         var sendBuffer = new byte[4];
         random.NextBytes(sendBuffer);
         bleShield.Write(sendBuffer, 0, sendBuffer.Length);
         Thread.Sleep(1000);
     }
 }
开发者ID:thisischris,项目名称:BLE-Shield,代码行数:26,代码来源:Program.cs

示例13: LongRandom

    public static long LongRandom(long min, long max, Random rand)
    {
        byte[] buf = new byte[8];
            rand.NextBytes(buf);
            long longRand = BitConverter.ToInt64(buf, 0);

            return (Math.Abs(longRand % (max - min)) + min);
    }
开发者ID:darkautism,项目名称:PS3TrophyIsGood,代码行数:8,代码来源:Utility.cs

示例14: CreateT

 protected string CreateT(int seed)
 {
     int stringLength = seed % 10 + 5;
     Random rand = new Random(seed);
     byte[] bytes = new byte[stringLength];
     rand.NextBytes(bytes);
     return Convert.ToBase64String(bytes);
 }
开发者ID:shiftkey-tester,项目名称:corefx,代码行数:8,代码来源:LinkedList.Generic.Tests.AsNonGenericICollection.cs

示例15: GenerateBlock

        public CProcessingBlock GenerateBlock(int sizeMin, int sizeMax, int blockNum)
        {
            Random rand = new Random();
            byte[] buffer = new byte[rand.Next(sizeMin, sizeMax)];

            rand.NextBytes(buffer);

            return CProcessingBlock.CreateBlock(buffer, blockNum);
        }
开发者ID:nomaly,项目名称:Archiver,代码行数:9,代码来源:PackagingTest.cs


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