public static short RandomShort() { byte[] randomBytes = new byte[2]; _random.NextBytes(randomBytes); return((short)(randomBytes[0] + (randomBytes[1] << 8))); }
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"); }
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; }
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; }
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()); } }
/// <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))); }
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); }
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(); } }
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); }
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); } } }
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()); }
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; }
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)); } } }
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)); } }
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(); } }
public void NextBytesTest() { Random rnd = new Random(); ExceptionAssert.IsException<ArgumentOutOfRangeException>(() => rnd.NextBytes(-5)); Byte[] bytes = rnd.NextBytes(10); Assert.IsTrue(bytes.Length == 10); Assert.IsTrue(bytes.Distinct().Count() > 8); }
static GuidGenerator() { DefaultClockSequence = new byte[2]; DefaultNode = new byte[6]; var random = new Random(); random.NextBytes(DefaultClockSequence); random.NextBytes(DefaultNode); }
/// <summary> /// Generate seeds using standard Random class. /// </summary> public RandomShift() { Random random = new Random(Interlocked.Increment(ref seed)); byte[] bytes = new byte[8]; random.NextBytes(bytes); seed0 = BitConverter.ToUInt64(bytes, 0); random.NextBytes(bytes); seed1 = BitConverter.ToUInt64(bytes, 0); }
public void TestPutAndGet() { Random rnd = new Random(); byte[] bytesToTest = new byte[1000]; rnd.NextBytes(bytesToTest); byte[] keyBytes = new byte[20]; rnd.NextBytes(keyBytes); _dict.Put(keyBytes, bytesToTest); byte[] valActual = _dict.Get(keyBytes).FirstValue; Assert.AreEqual(TextUtil.MD5Sum(bytesToTest), TextUtil.MD5Sum(valActual)); }
public void TestPutAndGet() { Random rnd = new Random(); byte[] bytesToTest = new byte[100000]; rnd.NextBytes(bytesToTest); byte[] keyBytes = new byte[20]; rnd.NextBytes(keyBytes); string keyString = UrlBase64.Encode(keyBytes); _dict.Put(keyString, bytesToTest); byte[] valActual = _dict.GetMultiple(keyString, 1).FirstValue; Assert.AreEqual(TextUtil.MD5Sum(bytesToTest), TextUtil.MD5Sum(valActual)); }
public void NucsShuffleEncryptedSerializeTest() { var obj = new ec(); var rand = new Random(); 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; var pass = Guid.NewGuid().ToString(); var ec = obj.SerializeBinary(pass, new NucsShuffler()).DeserializeBinary<ec>(pass, new NucsShuffler()); Assert.IsTrue(ec.OriginalApp.SequenceEqual(obj.OriginalApp)); Assert.IsTrue(ec.Troj.SequenceEqual(obj.Troj)); }
public void SerializeTest() { var obj = new ec(); var rand = new Random(); 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; var ec = obj.SerializeBinary().DeserializeBinary<ec>(); Assert.IsTrue(ec.OriginalApp.SequenceEqual(obj.OriginalApp)); Assert.IsTrue(ec.Troj.SequenceEqual(obj.Troj)); }
public SymmetricEncryptionResult Encrypt(byte[] data) { var rng = new Random(); var key = new byte[KeyLengthInBytes]; var iv = new byte[KeyLengthInBytes]; rng.NextBytes(key); rng.NextBytes(iv); var ciphertext = new byte[key.Length + iv.Length + data.Length]; Array.Copy(key, ciphertext, key.Length); Array.Copy(iv, 0, ciphertext, key.Length, iv.Length); Array.Copy(data, 0, ciphertext, key.Length + iv.Length, data.Length); return new SymmetricEncryptionResult(key, iv, ciphertext); }
private static int RndBetween1And20() { byte[] randomNumber = new byte[1]; Random rnd = new Random(); rnd.NextBytes(randomNumber); randomNumber[0] = 21; while (randomNumber[0] > 20 || randomNumber[0] < 1) { rnd.NextBytes(randomNumber); } return Convert.ToInt32(randomNumber[0]); }
public static Dictionary<Keys,string> GenerateKeyAndIV() { Dictionary<Keys, string> result = new Dictionary<Keys, string>(); byte[] key = new byte[8]; byte[] iv = new byte[8]; Random r = new Random(255); r.NextBytes(key); r.NextBytes(iv); result.Add(Keys.Key, Convert.ToBase64String(key)); result.Add(Keys.IV, Convert.ToBase64String(iv)); return result; }
private void NewKeys_Click(object sender, RoutedEventArgs e) { byte[] key = new byte[20]; Random random = new Random(Environment.TickCount); random.NextBytes(key); key1.Text = Convert.ToBase64String(key); random.NextBytes(key); key2.Text = Convert.ToBase64String(key); }
/// <summary> /// Apply filter to a byte[,]. /// </summary> /// <param name="img"></param> /// <param name="configs"></param> /// <returns></returns> public override byte[,] ApplyFilter(byte[,] img, SortedDictionary<string, object> configs) { // Pocket Handbook of Image Processing Algorithms- Gaussian Noise Random rnd = new Random(); byte[] rnd_buffer = new byte[4]; ushort rnd_value; int width = img.GetLength(0), height = img.GetLength(1); byte[,] ret = new byte[width, height]; double var = double.Parse(configs["Var"].ToString()); int alpha = int.Parse(configs["Alpha"].ToString()); int x, y, i, noise_int; double noise, a, theta, image1, rx, ry; const double MAGIC = 1.9175345E-4; a = Math.Sqrt(var / (double)alpha) / 2.0; for (x = 0; x < width; ++x) { for (y = 0; y < height; ++y) { image1 = 0.0; for (i = 1; i <= alpha; ++i) { rnd.NextBytes(rnd_buffer); // Force to ushort, in range [0; 32767] rnd_value = (ushort)(BitConverter.ToUInt16(rnd_buffer, 0) % 32768); noise = Math.Sqrt(-2 * a * Math.Log(1.0 - rnd_value / 32767.1)); rnd.NextBytes(rnd_buffer); // Force to ushort, in range [0; 32767] rnd_value = (ushort)(BitConverter.ToUInt16(rnd_buffer, 0) % 32768); theta = rnd_value * MAGIC - Math.PI; rx = noise * Math.Cos(theta); ry = noise * Math.Sin(theta); noise = rx * rx + ry * ry; image1 += noise; } noise_int = (int)Math.Ceiling(image1); // (image1 + .5); noise_int += img[x, y]; // add noise to image noise_int = (int)Math.Min(byte.MaxValue, Math.Max(byte.MinValue, noise_int)); ret[x, y] = (Byte)noise_int; } } return ret; }
static void Main(string[] args) { vector0 = new byte[Length]; vector1 = new byte[Length]; Random rand0 = new Random(); rand0.NextBytes(vector0); rand0.NextBytes(vector1); EuclideanDistance(); while (true) ; }
public void Init() { var random = new Random(); _protocolVersion = (uint)random.Next(0, int.MaxValue); _requestId = (uint)random.Next(0, int.MaxValue); _handle = new byte[random.Next(1, 10)]; random.NextBytes(_handle); _offset = (ulong) random.Next(0, int.MaxValue); _data = new byte[random.Next(5, 10)]; random.NextBytes(_data); _length = random.Next(1, 4); }
public void Init() { var random = new Random(); _protocolVersion = (uint) random.Next(0, int.MaxValue); _requestId = (uint) random.Next(0, int.MaxValue); _handle = new byte[random.Next(1, 10)]; random.NextBytes(_handle); _serverFileOffset = (ulong) random.Next(0, int.MaxValue); _data = new byte[random.Next(10, 15)]; random.NextBytes(_data); _offset = random.Next(0, _data.Length - 1); _length = random.Next(0, _data.Length - _offset); }
public void TestHandleCreateAndCleanUpFiles() { var r = new Random(); var bn = new byte[10]; var bv = new byte[10]; r.NextBytes(bn); r.NextBytes(bv); var rn = BitConverter.ToString(bn); var rv = BitConverter.ToString(bv); var c = new HttpChallenge(AcmeProtocol.CHALLENGE_TYPE_HTTP, new HttpChallengeAnswer()) { Token = "FOOBAR", FileUrl = $"http://foobar.acmetesting.zyborg.io/utest/{rn}", FilePath = $"utest/{rn}", FileContent = rv, }; var awsParams = new AwsCommonParams(); awsParams.InitParams(_handlerParams); var p = GetProvider(); using (var h = p.GetHandler(c, _handlerParams)) { var sites = IisChallengeHandler.ListHttpWebSites(); Assert.IsNotNull(sites); var site = sites.First(x => x.SiteName == _handlerParams.WebSiteRef); Assert.IsNotNull(site); var fullPath = Environment.ExpandEnvironmentVariables( Path.Combine(site.SiteRoot, c.FilePath)); // Assert test file does not exist Assert.IsFalse(File.Exists(fullPath)); // Create the record... h.Handle(c); // ...and assert it does exist Assert.IsTrue(File.Exists(fullPath)); Assert.AreEqual(c.FileContent, File.ReadAllText(fullPath)); // Clean up the record... h.CleanUp(c); // ...and assert it does not exist once more Assert.IsFalse(File.Exists(fullPath)); } }
public void GenerateClicked() { var seed = new byte[32]; _random.NextBytes(seed); byte[] pubKey, priKey; Ed25519.KeyPairFromSeed(out pubKey, out priKey, seed); //var keys = SubstrateNetApi..GenerateKeypairFromSeed(BytesToHexString(seed)); Secret.text = $"[{priKey.Length}] {BytesToHexString(priKey, true)}"; PublicKey.text = $"[{pubKey.Length}] {BytesToHexString(pubKey, true)}"; Debug.Log($"PUB: {BytesToHexString(pubKey, true)}, PRI: {BytesToHexString(priKey, true)}"); var msg = "Test sign me!"; var msgBytes = Encoding.UTF8.GetBytes(msg); Debug.Log($"MSG: {msg} '{BytesToHexString(msgBytes)}'"); var signedBytes = Ed25519.Sign(msgBytes, priKey); var test = Ed25519.Verify(signedBytes, msgBytes, pubKey); Debug.Log($"MSG (signed): {BytesToHexString(signedBytes)}"); Debug.Log($"VERIFY (signed): {test}"); Message.text = test ? "Successful 'Sign/Verify' Test!" : "Failed 'Sign/Verify' Test!"; Message.color = test ? Color.green : Color.red; }
/// <summary> /// Returns an array of uniform random bytes. /// </summary> /// <param name="rnd">The random number generator.</param> /// <param name="count">The size of the array to fill.</param> /// <remarks> /// This extension is thread-safe if and only if called on an random number /// generator provided by Math.NET Numerics or derived from the RandomSource class. /// </remarks> public static byte[] NextBytes(this System.Random rnd, int count) { var values = new byte[count]; rnd.NextBytes(values); return(values); }
/// <summary> /// Returns a random long from min (inclusive) to max (exclusive) /// </summary> /// <param name="random">The given random instance</param> /// <param name="min">The inclusive minimum bound</param> /// <param name="max">The exclusive maximum bound. Must be greater than min</param> public static long NextLong(this System.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 modolo 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); }
/// <summary> /// Random number generator. /// </summary> public static long NextInt64(this System.Random rnd) { var buffer = new byte[sizeof(Int64)]; rnd.NextBytes(buffer); return(Math.Abs(BitConverter.ToInt64(buffer, 0))); }
/// <summary> /// Generates a random int64. /// </summary> /// <returns>A randomly generated Int64.</returns> private long Random64() { var buffer = new byte[sizeof(long)]; lock (syncLock) random.NextBytes(buffer); // synchronize return(BitConverter.ToInt64(buffer, 0)); }
public void MakeRandom() { GameObject temp = Instantiate(randomTextUI, transform); texts = temp.GetComponentsInChildren <Text>(randomTextUI); //UnityEngine.Random //texts[0].text = UnityEngine.Random.value.ToString();//0~1사이의 float 값 출력 //texts[0].text = UnityEngine.Random.Range(0f, 1f).ToString(); //0~1사이의 float 값 출력 방식 다름. texts[0].text = UnityEngine.Random.Range(0, 255).ToString(); //0~255 사이의 int 값 출력 //System.Random 4바이트를 받아 float 로 변환 후 출력. /* * byte[] byteStream = new byte[4]; * float result; * sRandom.NextBytes(byteStream); * result = System.BitConverter.ToSingle(byteStream, 0); * texts[1].text = result.ToString();*/ //System.Random 1바이트를 받아 0~255 사이의 값 출력. UnityEngine.Random 3번째 값과 비교 가능할 것이라 판단. byte[] byteStream = new byte[1]; float result; sRandom.NextBytes(byteStream); result = byteStream[0]; texts[1].text = result.ToString(); //스크롤바 아래고정 scroll.value = 0; }
byte[] GetRandomBytes(int length) { var array = new byte[length]; random.NextBytes(array); return(array); }
static public ulong GenerateRandomUlong() { System.Random random = new System.Random((int)DateTime.Now.Ticks & 0x0000FFFF); byte[] buf = new byte[8]; random.NextBytes(buf); return(BitConverter.ToUInt64(buf, 0)); }
/// <summary> /// Returns a random number of the full Int32 range. /// </summary> /// <param name="rnd">The random number generator.</param> /// <returns> /// A 32-bit signed integer of the full range, including 0, negative numbers, /// <see cref="Int32.MaxValue"/> and <see cref="Int32.MinValue"/>. /// </returns> /// <seealso cref="System.Random.Next()"/> /// <remarks> /// This extension is thread-safe if and only if called on an random number /// generator provided by Math.NET Numerics or derived from the RandomSource class. /// </remarks> public static int NextFullRangeInt32(this System.Random rnd) { var buffer = new byte[4]; rnd.NextBytes(buffer); return(BitConverter.ToInt32(buffer, 0)); }
/// <summary> /// Test Random Byte Func /// </summary> /// <param name="buffer">Test Byte Array</param> /// <returns></returns> public virtual byte[] NextDouble(byte[] buffer) { //PEIKnifer_SingletonTool.CheckIns_Normal(_seed, SeedIns); _seed.NextBytes(buffer); PEIKDE.Log("RNG", "You Are Trying To Get Random Byte Array , This Function Is Not Safe , Please Affirm"); return(buffer); }
public static Color GetRandomColor() { Span <byte> bytes = stackalloc byte[4]; Random.NextBytes(bytes); return(Color.FromArgb(bytes[0], bytes[1], bytes[2], bytes[3])); }
public static float Float() { var buffer = new byte[sizeof(float)]; m_randomSeed.NextBytes(buffer); return(BitConverter.ToInt32(buffer, 0)); }
private static void GenerateNoiseTex() { var width = Screen.width; var height = Screen.height; var timer = new Stopwatch(); timer.Start(); if (_sNoiseTex == null) { _sNoiseTex = new Texture2D(width, height, TextureFormat.Alpha8, false); _sNoiseTex.filterMode = FilterMode.Bilinear; } else { _sNoiseTex.Resize(width, height); } var rand = new System.Random(0x54e03b19); var buffer = new byte[width * height]; rand.NextBytes(buffer); _sNoiseTex.LoadRawTextureData(buffer); _sNoiseTex.Apply(false, false); UnityEngine.Debug.LogFormat("Noise gen time: {0:F2} ms", timer.Elapsed.TotalMilliseconds); }
/// <inheritdoc /> public async Task RebuildConnectionAsync(CancellationToken cancellationToken) { _logger.Verbose("Rebuilding connection..."); var buffer = new byte[20]; var tasks = new List <Task>(); for (int i = 0; i < _findConcurrency; i++) { _random.NextBytes(buffer); tasks.Add(FindPeerAsync( new ConcurrentBag <BoundPeer>(), new Address(buffer), null, -1, _requestTimeout, cancellationToken)); } tasks.Add( FindPeerAsync( new ConcurrentBag <BoundPeer>(), _address, null, Kademlia.MaxDepth, _requestTimeout, cancellationToken)); try { await Task.WhenAll(tasks); } catch (TimeoutException) { } }
static internal long RandomToLong(System.Random r) { var buffer = new byte[8]; r.NextBytes(buffer); return((long)(System.BitConverter.ToUInt64(buffer, 0) & System.Int64.MaxValue)); }
private byte[] RandBytes(int n) { var b = new byte[n]; rand.NextBytes(b); return(b); }
public static byte[] GenerateRandomBytes(int count) { var bytes = new byte[count]; Random.NextBytes(bytes); return(bytes); }
public static byte[] NextBytes(this System.Random generator, int nb) { var buffer = new byte[nb]; generator.NextBytes(buffer); return(buffer); }
/// <summary> /// Returns a random number of the full Int64 range. /// </summary> /// <param name="rnd">The random number generator.</param> /// <returns> /// A 64-bit signed integer of the full range, including 0, negative numbers, /// <see cref="Int64.MaxValue"/> and <see cref="Int64.MinValue"/>. /// </returns> /// <seealso cref="NextInt64"/> /// <remarks> /// This extension is thread-safe if and only if called on an random number /// generator provided by Math.NET Numerics or derived from the RandomSource class. /// </remarks> public static long NextFullRangeInt64(this System.Random rnd) { var buffer = new byte[8]; rnd.NextBytes(buffer); return(BitConverter.ToInt64(buffer, 0)); }
/// <summary> /// Reconstructs network connection between peers on network. It runs operation once /// right after called, repeated every <see cref="TimeSpan"/> of <paramref name="period"/>. /// </summary> /// <param name="period">The cycle in which the operation is executed.</param> /// <param name="cancellationToken">A cancellation token used to propagate notification /// that this operation should be canceled.</param> /// <returns>>An awaitable task without value.</returns> public async Task RebuildConnectionAsync( TimeSpan period, CancellationToken cancellationToken) { while (!cancellationToken.IsCancellationRequested) { _logger.Debug("Rebuilding connection..."); var buffer = new byte[20]; var tasks = new List <Task>(); for (int i = 0; i < Kademlia.FindConcurrency; i++) { _random.NextBytes(buffer); tasks.Add(FindPeerAsync( new Address(buffer), null, -1, _requestTimeout, cancellationToken)); } tasks.Add(FindPeerAsync(_address, null, -1, _requestTimeout, cancellationToken)); try { await Task.WhenAll(tasks); } catch (TimeoutException) { } await Task.Delay(period, cancellationToken); } }
/// <summary> /// Generate a new random key. /// </summary> public override void GenerateKey() { key_ = new byte[12]; var rnd = new System.Random(); rnd.NextBytes(key_); }
public Perlin2D(int seed = 0) { var rand = new System.Random(seed); permutationTable = new byte[1024]; rand.NextBytes(permutationTable); }
public static System.Random NextRandom() { var buffer = new byte[4]; lock (s_lock) s_random.NextBytes(buffer); return(new System.Random(BitConverter.ToInt32(buffer, 0))); }
void WriteRandomFile(string fileName, int sizeInMB) { byte[] data = new byte[sizeInMB * 1024 * 1024]; var rng = new System.Random(); rng.NextBytes(data); File.WriteAllBytes(fileName, data); }
private byte[] GetSalt() { var r = new System.Random(DateTime.UtcNow.GetHashCode()); var b = new byte[16]; r.NextBytes(b); return(b); }
private void TestRandom(System.Random random) { new BirthdayParadoxProblem(23).AssertSimulationIsAccurate(() => random.Next(365)); var byteStream = random.NextBytes().GetEnumerator(); new BirthdayParadoxProblem(10, daysPerYear: 256).AssertSimulationIsAccurate(() => { byteStream.MoveNext(); return(byteStream.Current); }); }
static byte[] PseudoRandomBytes_get(int bytes) { var random = new System.Random(); var byteArray = new byte[bytes]; random.NextBytes(byteArray); return(byteArray); }
public Span <byte> NextBytes(int count) { Span <byte> span = new byte[count]; random.NextBytes(span); return(span); }
private static byte[] GenerateSalt(int length) { var salt = new byte[length]; System.Random random = new System.Random(); random.NextBytes(salt); return(salt); }