/// <summary> /// Produces a random array of <see cref="byte"/>s. /// </summary> /// <param name="length"> /// The length of the array. /// </param> /// <returns> /// An array of <see cref="byte"/>s. /// </returns> public static byte[] NextBytes(long length = 16) { var buffer = new byte[length]; RandomGenerator.NextBytes(buffer); return(buffer); }
public void Test_SHA1_SHA256() { var random = new System.Random(123); var bytes512 = new byte[512]; random.NextBytes(bytes512); var output = new byte[20]; var sha1managed = new SHA1Managed(); byte[] tmp1 = null; uint[] tmp2 = null; for (int dataLength = 0; dataLength < bytes512.Length; dataLength++) { SHA.ComputeSHA1(bytes512, dataLength, output, 0, ref tmp1, ref tmp2); Assert.AreEqual(sha1managed.ComputeHash(new ByteBuffer(bytes512, 0, dataLength).ToArray()), output); } output = new byte[32]; var sha256managed = new SHA256Managed(); for (int dataLength = 0; dataLength < bytes512.Length; dataLength++) { SHA.ComputeSHA256(bytes512, dataLength, output, 0, ref tmp1, ref tmp2); Assert.AreEqual(sha256managed.ComputeHash(new ByteBuffer(bytes512, 0, dataLength).ToArray()), output); } var key = new byte[64]; random.NextBytes(key); output = new byte[20]; for (int keyLength = 0; keyLength < key.Length; keyLength++) { for (int dataLength = 0; dataLength < bytes512.Length; dataLength++) { HMAC_SHA1.ComputeHmacSha1(new ByteBuffer(key, 0, keyLength), new ByteBuffer(bytes512, 0, dataLength), output, 0); Assert.AreEqual(new HMACSHA1(new ByteBuffer(key, 0, keyLength).ToArray()).ComputeHash(bytes512, 0, dataLength), output); } } HMAC_SHA1.ComputeHmacSha1(new ByteBuffer(key, 0, key.Length), new ByteBuffer(bytes512, 40, 200), output, 0); Assert.AreEqual(new HMACSHA1(key).ComputeHash(bytes512, 40, 200), output); }
private static void CreateRandomFile(string path, long size, System.Random random) { var data = new byte[size]; random.NextBytes(data); File.WriteAllBytes(path, data); }
public Perlin2D(int seed = 0) { var rand = new System.Random(seed); permutationTable = new byte[1024]; rand.NextBytes(permutationTable); }
public static Guid NewGuid() { byte[] bytes = new byte[16]; System.Random random = new System.Random(); random.NextBytes(bytes); return(new Guid(bytes)); }
public void TestVerfitySign10KParallel() { //init data; Logger.LogMessage("begin testsign1000"); byte[] testdata = new byte[4096]; System.Random ran = new System.Random(); System.DateTime begin = System.DateTime.Now; var prikey = new byte[32]; ran.NextBytes(prikey); var signer = Allpet.Helper_NEO.Signer.FromPriKey(prikey); var pubkey = Allpet.Helper_NEO.GetPublicKey_FromPrivateKey(prikey); var signdata = signer.Sign(testdata); var unsigner = Allpet.Helper_NEO.Signer.FromPubkey(pubkey); var vi = 0; Parallel.For(0, 10000, (i) => { var b = unsigner.Verify(testdata, signdata); if (b) { vi++; } }); System.DateTime end = System.DateTime.Now; Logger.LogMessage("end testunsign1000:" + (end - begin).TotalSeconds); Logger.LogMessage("end testunsign1000 vi=" + vi); }
public void TestSign10KParallel() { //init data; Logger.LogMessage("begin testsign1000"); byte[] testdata = new byte[4096]; System.Random ran = new System.Random(); System.DateTime begin = System.DateTime.Now; var prikey = new byte[32]; ran.NextBytes(prikey); var signer = Allpet.Helper_NEO.Signer.FromPriKey(prikey); Parallel.For(0, 10000, (i) => { var signdata = signer.Sign(testdata); }); //for (var i = 0; i < 1000; i++) //{ // //ran.NextBytes(testdata); //} System.DateTime end = System.DateTime.Now; Logger.LogMessage("end testsign1000:" + (end - begin).TotalSeconds); }
public void TestSend() { var fp = FragPipe.Instance; var head_c = new HeaderChop(new PType("frag").ToMemBlock()); fp.Subscribe(head_c, null); var fh = new FragmentingHandler(1000); head_c.Subscribe(fh, null); var th = new TestHandler(); fh.Subscribe(th, null); head_c.WithoutHeader.Subscribe(th, null); var fs = new FragmentingSender(100, fp); var r = new System.Random(); for (int length = 1; length < 10000; length++) { var buf = new byte[length]; r.NextBytes(buf); var dat = MemBlock.Reference(buf); fs.Send(dat); //This will do the assert. Assert.AreEqual(dat, th.LastData, "Data was received"); } }
public IEnumerator WriteAllBytesShouldCreateFileTest() { var testData = new byte[1024]; var pathToTestFile = $"~{nameof(WriteAllBytesShouldCreateFileTest)}"; var random = new Random(); random.NextBytes(testData); yield return(FileRoutine.WriteAllBytesRoutine(pathToTestFile, testData) .Self(out var writeAllBytesRoutine)); if (writeAllBytesRoutine.IsError) { File.Delete(pathToTestFile); Assert.Fail(); } var afterWriteData = File.ReadAllBytes(pathToTestFile); File.Delete(pathToTestFile); Assert.AreEqual(afterWriteData.Length, testData.Length); for (int i = 0; i < afterWriteData.Length; i++) { if (afterWriteData[i] != testData[i]) { Assert.Fail( $"Arrays {nameof(afterWriteData)} and {nameof(testData)} are not equals (element №{i})"); } } }
public IEnumerator ReadAllBytesShouldReadBytesInFileTest() { var testData = new byte[1024]; var pathToTestFile = $"~{nameof(ReadAllBytesShouldReadBytesInFileTest)}"; var random = new Random(); random.NextBytes(testData); File.WriteAllBytes(pathToTestFile, testData); yield return(FileRoutine.ReadAllBytesRoutine(pathToTestFile) .Result(out var readAllBytesResult)); File.Delete(pathToTestFile); if (readAllBytesResult.Routine.IsError) { throw readAllBytesResult.Routine.Exception; } var readData = readAllBytesResult.Result; Assert.AreEqual(readData.Length, testData.Length); for (int i = 0; i < readData.Length; i++) { if (readData[i] != testData[i]) { Assert.Fail($"Arrays {nameof(readData)} and {nameof(testData)} are not equals (element №{i})"); } } }
static void Main(string[] args) { var image1 = System.Drawing.Image.FromFile("tumblr_mwiiixNSpW1qbkusho1_1280.png"); //Debugger.Break(); var image2 = new System.Windows.Media.Imaging.BitmapImage(); image2.BeginInit(); image2.UriSource = new System.Uri("tumblr_mwiiixNSpW1qbkusho1_1280.png", System.UriKind.Relative); image2.EndInit(); //Debugger.Break(); var image3 = new System.Windows.Media.Imaging.BitmapImage(); image3.BeginInit(); image3.StreamSource = new System.IO.FileStream("VisualStudio256_256.png", System.IO.FileMode.Open); image3.EndInit(); //Debugger.Break(); var pixelFormat = System.Windows.Media.PixelFormats.Bgr32; int width = 1280; int height = 720; int rawStride = (width * pixelFormat.BitsPerPixel + 7) / 8; byte[] rawImage = new byte[rawStride * height]; var value = new System.Random(); value.NextBytes(rawImage); var image4 = System.Windows.Media.Imaging.BitmapSource.Create(width, height, 96, 96, pixelFormat, null, rawImage, rawStride); System.Diagnostics.Debugger.Break(); }
public long GetLongRandom() { var buffer = new byte[8]; m_Random.NextBytes(buffer); return((long)(System.BitConverter.ToUInt64(buffer, 0) & System.Int64.MaxValue)); }
public void Hashes_WithSameAlgorithm_CanHashParallel() { var testResults = Enumerable.Repeat(0, 1000) .Select(_ => { var randomBytes = _random.NextBytes(100); var inputStreamForExpected = new MemoryStream(randomBytes); var inputStreamForHash = new MemoryStream(randomBytes); var expectedByteArray = Instance.ComputeHash(inputStreamForExpected); return(expected: expectedByteArray, dataToTest: inputStreamForHash); }) .ToArray() .Select(tuple => { var(expectedByteArray, inputStreamForHash) = tuple; var hashMock = new Mock <StreamHash>( inputStreamForHash, Instance) { CallBase = true }.Object; return(expected: expectedByteArray, actual: hashMock.Bytes); }) .AsParallel().ToArray(); foreach (var(expected, actual) in testResults) { Check.That(actual).ContainsExactly(expected); } }
public static void NextBytes(byte[] buffer) { lock (m_Lock) { m_Random.NextBytes(buffer); } }
public static string NewGUID() { System.DateTime dt = System.DateTime.Now; long tick = dt.Ticks; byte[] b = new byte[10]; random.NextBytes(b); ushort s3, s4, s5; s3 = (ushort)(tick); s4 = (ushort)((long)tick >> 16); s5 = (ushort)((long)tick >> 32); return(b[0].ToString("X").PadLeft(2, '0') + b[1].ToString("X").PadLeft(2, '0') + b[2].ToString("X").PadLeft(2, '0') + b[3].ToString("X").PadLeft(2, '0') + "-" + s5.ToString("X").PadLeft(4, '0') + "-" + s4.ToString("X").PadLeft(4, '0') + "-" + s3.ToString("X").PadLeft(4, '0') + "-" + b[4].ToString("X").PadLeft(2, '0') + b[5].ToString("X").PadLeft(2, '0') + b[6].ToString("X").PadLeft(2, '0') + b[7].ToString("X").PadLeft(2, '0') + b[8].ToString("X").PadLeft(2, '0') + b[9].ToString("X").PadLeft(2, '0')); }
public void EncryptDecrypt() { var random = new Random(); var buffer = new byte[4096]; random.NextBytes(buffer); ImmutableArray <byte> key = ImmutableArray.Create(buffer, 0, 16); random.NextBytes(buffer); ImmutableArray <byte> value = buffer.ToImmutableArray(); T c = Cipher; ImmutableArray <byte> encrypted = c.Encrypt(key, value); ImmutableArray <byte> decrypted = c.Decrypt(key, encrypted); TestUtils.AssertBytesEqual(value, decrypted); }
public static Guid NewGuid() { var bytes = new byte[16]; random.NextBytes(bytes); return(new Guid(bytes)); }
public void BVT_TunnelSCSIPersistentReserve_RegisterAndReserve() { BaseTestSite.Log.Add(LogEntryKind.TestStep, "1. Client opens a shared virtual disk file and expects success."); OpenSharedVHD(TestConfig.NameOfSharedVHDX, RSVD_PROTOCOL_VERSION.RSVD_PROTOCOL_VERSION_1); BaseTestSite.Log.Add(LogEntryKind.TestStep, "2. Client sends Register service action of SCSI Persistent Reserve Out command by tunnel operation RSVD_TUNNEL_SCSI_OPERATION to server and expects success."); System.Random random = new System.Random(); byte[] key = new byte[8]; random.NextBytes(key); byte scsiStatus; SendAndReceiveSCSICommand( this.client, 10, // The size of SCSI Persistent Reserve Out command is 10 CreateCDBBuffer_PersistentReserveOut(PERSISTENT_RESERVE_OUT_SERVICE_ACTION.REGISTER_AND_IGNORE_EXISTING_KEY, 0), CreateDataBuffer_PersistentReserveOut(0, System.BitConverter.ToUInt64(key, 0)), out scsiStatus); VerifyFieldInResponse("SCSIStatus", 0, scsiStatus); // Status code 0 indicates that the device has completed the task successfully. BaseTestSite.Log.Add(LogEntryKind.TestStep, "3. Client sends Reserve service action of SCSI Persistent Reserve Out command by tunnel operation RSVD_TUNNEL_SCSI_OPERATION to server and expects success."); SendAndReceiveSCSICommand( this.client, 10, CreateCDBBuffer_PersistentReserveOut(PERSISTENT_RESERVE_OUT_SERVICE_ACTION.RESERVE, PERSISTENT_RESERVATION_SCOPE_AND_TYPE_CODE.WriteExclusiveRegistrantsOnly), CreateDataBuffer_PersistentReserveOut(System.BitConverter.ToUInt64(key, 0), 0), out scsiStatus); VerifyFieldInResponse("SCSIStatus", 0, scsiStatus); BaseTestSite.Log.Add(LogEntryKind.TestStep, "4. Client closes the file."); client.CloseSharedVirtualDisk(); }
public void Test() { System.Random r = new System.Random(); for (int i = 0; i < 1024; i++) { //Test ClassOf and SetClass: int c = r.Next(160); byte[] buf0 = new byte[Address.MemSize]; //Fill it with junk r.NextBytes(buf0); Address.SetClass(buf0, c); int c2 = Address.ClassOf(MemBlock.Reference(buf0, 0, Address.MemSize)); Assert.AreEqual(c, c2, "Class Round Trip"); //Test BigInteger stuff: int size = r.Next(1, MemSize + 1); byte[] buf1 = new byte[size]; r.NextBytes(buf1); BigInteger b1 = new BigInteger(buf1); byte[] buf2 = Address.ConvertToAddressBuffer(b1); //Check to see if the bytes are equivalent: int min_len = System.Math.Min(buf1.Length, buf2.Length); bool all_eq = true; for (int j = 0; j < min_len; j++) { all_eq = all_eq && (buf2[buf2.Length - j - 1] == buf1[buf1.Length - j - 1]); } if (!all_eq) { System.Console.Error.WriteLine("Buf1: "); foreach (byte b in buf1) { System.Console.Write("{0} ", b); } System.Console.Error.WriteLine(); System.Console.Error.WriteLine("Buf2: "); foreach (byte b in buf2) { System.Console.Write("{0} ", b); } System.Console.Error.WriteLine(); } Assert.IsTrue(all_eq, "bytes are equivalent"); BigInteger b2 = new BigInteger(buf2); Assert.AreEqual(b1, b2, "BigInteger round trip"); } }
public static byte[] RandomBytes(int length) { var random = new System.Random(Time.Now); var bytes = new byte[length]; random.NextBytes(bytes); return(bytes); }
/// <summary> /// Draw an array of random and uniform bytes. /// </summary> /// <param name="length">The array length requested.</param> public sealed override byte[] Bytes(int length) { byte[] arr = new byte[length]; Rand.NextBytes(arr); return(arr); }
public static unsafe void tst_NanOrInf_Representation2(afh.Application.Log log) { //double inf_d=double.PositiveInfinity; long inf = 0x7ff0000000000000; //*(long*)(&inf_d); int i = 0, pinf = 0, ninf = 0, nan = 0; System.Random r = new System.Random(); byte[] buff = new byte[8]; fixed(byte *p = buff) { long *plong = (long *)p; for (i = 0; i < 0x100000; i++) { r.NextBytes(buff); *plong |= inf; // 0x0123456789ABCDEF //*plong&=~0x4000000000000000; //*plong&=~0x2000000000000000; //*plong&=~0x1000000000000000; //*plong&=~0x0800000000000000; //*plong&=~0x0400000000000000; //*plong&=~0x0200000000000000; //*plong&=~0x0100000000000000; //*plong&=~0x0080000000000000; //*plong&=~0x0040000000000000; //*plong&=~0x0020000000000000; //*plong&=~0x0010000000000000; //・ ↑ のどれか一つでも実行すると全て finite になる //・ 何も実行しないと全て NaN に為る (∞ が出ないのは確率的な問題) //→ と言う事は、finite かどうかは (value&0x7fff....!=0x7fff...) を調べれば良さそう? double val = 0 + *(double *)plong; if (double.IsPositiveInfinity(val)) { pinf++; } else if (double.IsNegativeInfinity(val)) { ninf++; } else if (double.IsNaN(val)) { nan++; } } } i -= pinf + ninf + nan; log.WriteVar("+∞", pinf.ToString()); log.WriteVar("-∞", ninf.ToString()); log.WriteVar("NaN", nan.ToString()); log.WriteVar("finite", i.ToString()); }
/// <summary> /// Generates a salt value suitable for use in orders and 0x transactions /// </summary> /// <returns>Value in range (0, UINT256_MAX)</returns> public static BigInteger GenerateSalt() { byte[] randomInt = new byte[33]; lock (_randLock) _random.NextBytes(randomInt); randomInt[32] = 0; // Ensure we will not generate negative value return(new BigInteger(randomInt)); }
internal void TestRSA() { var data = new byte[32]; var r = new Random(); var user = new byte[64]; var pass = new byte[64]; r.NextBytes(user); r.NextBytes(pass); var rsaKeyPair = Crypto.DeriveRsaKey(user, pass); r.NextBytes(data); data[data.Length-1] = 0; Assert.AreEqual(data.Length, Crypto.DecryptRsa(Crypto.EncryptRsa(data, rsaKeyPair.Public), rsaKeyPair).Length); }
internal void TestRSAEncryption() { var user = new byte[64]; var pass = new byte[64]; var r = new Random(); r.NextBytes(user); r.NextBytes(pass); var keyPair = Crypto.DeriveRsaKey(user, pass); var data = new byte[64]; r.NextBytes(data); var encrypted = Crypto.EncryptRsa(data, keyPair.Public); Assert.AreElementsNotEqual(data, encrypted); var decrypted = Crypto.DecryptRsa(encrypted, keyPair); Assert.AreElementsEqual(data, decrypted); }
protected byte[] createRandomData(int id) { // random size messages byte[] buffer = new byte[rand.Next(10, 1000)]; // fill array with random rand.NextBytes(buffer); // first bytes can be ID buffer[0] = (byte)id; return(buffer); }
public static IEnumerable <BigInteger> RandomSigned(int count) { var rand = new System.Random(); byte[] data = new byte[256 / 8]; for (int i = 0; i < count; i++) { rand.NextBytes(data); yield return(new BigInteger(data)); } }
public static IEnumerable <BigInteger> RandomUnsigned(int count) { var rand = new System.Random(Seed); byte[] data = new byte[256 / 8]; for (int i = 0; i < count; i++) { rand.NextBytes(data); data[data.Length - 1] &= (byte)0x7F; yield return(new BigInteger(data)); } }
public void TestImplode() { System.Random r = new System.Random(); byte[] bytes = new byte[512]; r.NextBytes(bytes); var imploded = Implode.DoImplode(bytes); var exploded = ArxIO.Unpack(imploded); compare("imploded exploded", bytes, exploded); Debug.Log("test done"); }
/// <summary> /// 指定の乱数ジェネレータをテスト /// </summary> /// <param name="random"></param> /// <returns></returns> static string _Test(System.Random random) { var logText = new System.Text.StringBuilder(); for (int i = 0; i < 10; i++) { var v = random.NextDouble(); if (v < 0 || v >= 1) { Utility.DebugLogError("random.NextDouble()=" + v); } logText.AppendLine("random.NextDouble() = " + v); } for (int i = 0; i < 10; i++) { var v = random.Next(); if (v < 0) { Utility.DebugLogError("random.Next()=" + v); } logText.AppendLine("random.Next() = " + v); } for (int i = 0; i < 10; i++) { var v = random.Next(3); if (v < 0 || v >= 3) { Utility.DebugLogError("random.Next(3)=" + v); } logText.AppendLine("random.Next(3) = " + v); } for (int i = 0; i < 10; i++) { var v = random.Next(1, 3); if (v < 1 || v >= 3) { Utility.DebugLogError("random.Next(1, 3)=" + v); } logText.AppendLine("random.Next(1, 3) = " + v); } logText.AppendLine("random.NextBytes() = {"); var bytes = new byte[16]; random.NextBytes(bytes); foreach (var item in bytes) { logText.AppendLine(item.ToString()); } logText.AppendLine("}"); return(logText.ToString()); }
private void DOTest(Stream stream, uint serverID) { // System.Action timeoutAction = () => { // endPoint.Close(); // conn.Close(); // Debug.Log("timeout."); // }; endPoint = new EndPoint(stream, 1000, 5000, null); conn = endPoint.Dial(serverID); var random = new System.Random(); Thread.Sleep(1000 * 1); Debug.LogFormat("ConnID:{0}, RemoteID:{1}", conn.ID, conn.RemoteID); for (int i = 0; i < 100; i++) { var n = random.Next(10, 2000); var msg1 = new byte[n]; random.NextBytes(msg1); Assert.IsTrue(conn.Send(msg1)); byte[] msg2 = null; for (; ;) { msg2 = conn.Receive(); Assert.NotNull(msg2); if (msg2 == Conn.NoMsg) { continue; } break; } Assert.AreEqual(msg1.Length, msg2.Length); for (var j = 0; j < n; j++) { Assert.AreEqual(msg1[j], msg2[j]); } Debug.LogFormat("{0}, {1}", i, msg1.Length); } conn.Close(); }
private ulong RandomUlong() { var buffer = new byte[8]; random.NextBytes(buffer); ulong value = 0; for (var offset = 0; offset < 8; offset++) { value <<= 8; value |= buffer[offset]; } return(value); }
public void TestSend() { var fp = FragPipe.Instance; var head_c = new HeaderChop(new PType("frag").ToMemBlock()); fp.Subscribe(head_c, null); var fh = new FragmentingHandler(1000); head_c.Subscribe(fh, null); var th = new TestHandler(); fh.Subscribe(th, null); head_c.WithoutHeader.Subscribe(th, null); var fs = new FragmentingSender(100, fp); var r = new System.Random(); for(int length = 1; length < 10000; length++) { var buf = new byte[length]; r.NextBytes(buf); var dat = MemBlock.Reference(buf); fs.Send(dat); //This will do the assert. Assert.AreEqual(dat, th.LastData, "Data was received"); } }
public void SomeInsanityTests() { byte[] data; bool got_x; MemBlock b; System.Random r = new System.Random(); for(int i = 0; i < 100; i++) { int size = r.Next(1024); data = new byte[size]; r.NextBytes(data); int overshoot = r.Next(1,1024); got_x = false; b = null; try { //Should throw an exception: b = MemBlock.Reference(data, 0, size + overshoot); } catch { got_x = true; } Assert.IsNull(b, "Reference failure test"); Assert.IsTrue(got_x, "Exception catch test"); overshoot = r.Next(1,1024); got_x = false; b = MemBlock.Reference(data); try { //Should throw an exception: byte tmp = b[size + overshoot]; } catch { got_x = true; } Assert.IsTrue(got_x, "index out of range exception"); got_x = false; try { //Should throw an exception: byte tmp = b[ b.Length ]; } catch { got_x = true; } Assert.IsTrue(got_x, "index out of range exception"); } }
public void Test() { System.Random r = new System.Random(); byte[] data; for(int i = 0; i < 100; i++) { data = new byte[ r.Next(1024) ]; r.NextBytes(data); int offset = r.Next(data.Length); MemBlock mb1 = new MemBlock(data, 0, data.Length); MemBlock mb1a = MemBlock.Copy(data, 0, data.Length); Assert.AreEqual(mb1, mb1a, "MemBlock.Copy"); Assert.AreEqual(mb1, data, "MemBlock == byte[]"); MemBlock mb2 = new MemBlock(data, offset, data.Length - offset); MemBlock mb2a = mb1.Slice(offset); MemBlock mb3 = new MemBlock(data, 0, offset); MemBlock mb3a = mb1.Slice(0, offset); Assert.IsTrue(mb3.Equals( mb3a ), "mb3.Equals(mb3a)"); Assert.IsTrue(mb3a.Equals( mb3 ), "mb3a.Equals(mb3)"); Assert.AreEqual(mb3.CompareTo(mb2) + mb2.CompareTo(mb3), 0, "CompareTo"); Assert.IsTrue(mb2.Equals( mb2a ), "mb2.Equals(mb2a)"); Assert.IsTrue(mb2a.Equals( mb2 ), "mb2a.Equals(mb2)"); MemBlock cat = MemBlock.Concat(mb3, mb2); MemBlock cata = MemBlock.Concat(mb3a, mb2a); Assert.IsTrue(cat.Equals(cata), "Concat Equals"); Assert.IsTrue(cata.Equals(cat), "Concat a Equals"); Assert.IsTrue(mb1.Equals(cat), "Concat Equals Original"); if( offset != 0 ) { //These should not be equal Assert.IsFalse(mb2.Equals(mb1), "mb2 != mb1"); } int mb2a_l = mb2a.Length; byte[] tmp_data = new byte[mb2a_l]; mb2a.CopyTo(tmp_data, 0); MemBlock mb2b = new MemBlock(tmp_data, 0, tmp_data.Length); Assert.IsTrue(mb2a.Equals(mb2b), "mb2a.Equals(mb2b)"); Assert.IsTrue(mb2b.Equals(mb2a), "mb2b.Equals(mb2a)"); //Check the Hash: Assert.AreEqual(mb2b.GetHashCode(), mb2a.GetHashCode(), "GetHashCode"); //Here are some manual equality testing using the indexer bool all_equals = true; int j = 0; while( all_equals && (j < mb1.Length) ) { all_equals = (mb1[ j ] == cat[ j ]); j++; } Assert.IsTrue(all_equals, "Manual equality test mb1"); all_equals = true; j = 0; while( all_equals && (j < mb2.Length) ) { all_equals = (mb2[ j ] == mb2a[ j ]); j++; } Assert.IsTrue(all_equals, "Manual equality test mb2"); all_equals = true; j = 0; while( all_equals && (j < mb2.Length) ) { all_equals = (mb2[ j ] == mb2b[ j ]); j++; } Assert.IsTrue(all_equals, "Manual equality test mb2b"); } }
internal void TestRSASigning() { var user = new byte[64]; var pass = new byte[64]; var r = new Random(); r.NextBytes(user); r.NextBytes(pass); var keyPair = Crypto.DeriveRsaKey(user, pass); var data = new byte[64]; r.NextBytes(data); var signature = Crypto.Sign(data, keyPair); Assert.IsTrue(Crypto.VerifySignature(data, keyPair.Public, signature)); signature[0] = (byte) ~signature[0]; Assert.IsFalse(Crypto.VerifySignature(data, keyPair.Public, signature)); signature[0] = (byte) ~signature[0]; data[0] = (byte) ~data[0]; Assert.IsFalse(Crypto.VerifySignature(data, keyPair.Public, signature)); }
public void Test() { System.Random r = new System.Random(); //Test numeric type codes: for(int i = 1; i < 32; i++ ) { PType p = new PType(i); MemBlock b = p.ToMemBlock(); byte[] buf = new byte[100]; r.NextBytes(buf); //Get some junk: MemBlock junk = MemBlock.Reference(buf); MemBlock b1 = MemBlock.Concat(b, junk); MemBlock rest = null; PType pp = PType.Parse(b1, out rest); byte[] buf2 = new byte[1]; buf2[0] = (byte)i; MemBlock b2 = MemBlock.Reference(buf2); Assert.AreEqual(p, pp, System.String.Format("Round trip int: {0}", i)); Assert.AreEqual( b, b2, System.String.Format("Convert to MemBlock int: {0}", i) ); Assert.AreEqual(i, pp.TypeNumber, "Typenumber equality"); Assert.AreEqual(rest, junk, "rest in int PType"); } //Test string types: for(int i = 0; i < 1000; i++) { //Make a random string: // byte[] buf = new byte[ r.Next(1, 100) ]; r.NextBytes(buf); string s = Base32.Encode(buf); PType p1 = new PType(s); r.NextBytes(buf); //Get some junk: MemBlock b = MemBlock.Copy(buf); MemBlock combine = MemBlock.Concat( p1.ToMemBlock(), b); MemBlock b2 = null; PType p2 = PType.Parse(combine, out b2); Assert.AreEqual( p1, p2, "Round trip string: " + s); Assert.AreEqual( b, b2, "Round trip rest" ); Assert.AreEqual( s, p2.ToString(), "Round trip to string"); Assert.AreEqual( s, p1.ToString(), "Round trip to string"); Assert.AreEqual( p1.TypeNumber, p2.TypeNumber, "RT: TypeNumber test"); } //Test all one byte ascii strings: for(byte b = 32; b < ASCII_UPPER_BOUND; b++) { MemBlock raw = MemBlock.Reference( new byte[]{ b, 0 } ); MemBlock rest; PType p1 = PType.Parse(raw, out rest); Assert.AreEqual(rest, MemBlock.Null, "Rest is null"); PType p2 = PType.Parse(raw, out rest); Assert.AreEqual(rest, MemBlock.Null, "Rest is null"); Assert.IsTrue(p1 == p2, "reference equality of single byte type"); Assert.AreEqual(p1, p2, "equality of single byte type"); Assert.AreEqual(p1, new PType(p1.ToString()), "Round trip string"); } //Test TypeNumber of string types: for(int i = 0; i < 100; i++) { byte[] buf = new byte[20]; r.NextBytes(buf); for( int j = 1; j < 4; j++) { string s = Base32.Encode(buf).Substring(0, j); PType p1 = new PType(s); byte[] buf2 = System.Text.Encoding.UTF8.GetBytes(s); int t = 0; for(int k = 0; k < buf2.Length; k++) { t = t | buf2[k]; t <<= 8; } Assert.AreEqual(t, p1.TypeNumber, System.String.Format("String type number: {0}, s={1}", t, s) ); } } //Console.Error.WriteLine("Tested PType"); }
public void BVT_TunnelSCSIPersistentReserve_Preempt() { BaseTestSite.Log.Add(LogEntryKind.TestStep, "1. The first client opens a shared virtual disk file and expects success."); OpenSharedVHD(TestConfig.NameOfSharedVHDX, RSVD_PROTOCOL_VERSION.RSVD_PROTOCOL_VERSION_1); BaseTestSite.Log.Add(LogEntryKind.TestStep, "2. The second client opens a shared virtual disk file and expects success."); OpenSharedVHD(TestConfig.NameOfSharedVHDX, RSVD_PROTOCOL_VERSION.RSVD_PROTOCOL_VERSION_1, 0, true, secondClient, "client02"); System.Random random = new System.Random(); byte[] firstReservationkey = new byte[8]; random.NextBytes(firstReservationkey); byte[] secondReservationKey = new byte[8]; random.NextBytes(secondReservationKey); BaseTestSite.Log.Add(LogEntryKind.TestStep, "3. The first client sends Register service action of SCSI Persistent Reserve Out command by tunnel operation RSVD_TUNNEL_SCSI_OPERATION to server and expects success."); byte scsiStatus; SendAndReceiveSCSICommand( this.client, 10, CreateCDBBuffer_PersistentReserveOut(PERSISTENT_RESERVE_OUT_SERVICE_ACTION.REGISTER_AND_IGNORE_EXISTING_KEY, 0), CreateDataBuffer_PersistentReserveOut(0, System.BitConverter.ToUInt64(firstReservationkey, 0)), out scsiStatus); VerifyFieldInResponse("SCSIStatus", 0, scsiStatus); // Status code 0 indicates that the device has completed the task successfully. BaseTestSite.Log.Add(LogEntryKind.TestStep, "4. The first client sends Reserve service action of SCSI Persistent Reserve Out command by tunnel operation RSVD_TUNNEL_SCSI_OPERATION to server and expects success."); SendAndReceiveSCSICommand( this.client, 10, CreateCDBBuffer_PersistentReserveOut(PERSISTENT_RESERVE_OUT_SERVICE_ACTION.RESERVE, PERSISTENT_RESERVATION_SCOPE_AND_TYPE_CODE.WriteExclusiveRegistrantsOnly), CreateDataBuffer_PersistentReserveOut(System.BitConverter.ToUInt64(firstReservationkey, 0), 0), out scsiStatus); VerifyFieldInResponse("SCSIStatus", 0, scsiStatus); // Status code 0 indicates that the device has completed the task successfully. BaseTestSite.Log.Add(LogEntryKind.TestStep, "5. The second client sends Register service action of SCSI Persistent Reserve Out command by tunnel operation RSVD_TUNNEL_SCSI_OPERATION to server and expects success."); SendAndReceiveSCSICommand( secondClient, 10, CreateCDBBuffer_PersistentReserveOut(PERSISTENT_RESERVE_OUT_SERVICE_ACTION.REGISTER_AND_IGNORE_EXISTING_KEY, 0), CreateDataBuffer_PersistentReserveOut(0, System.BitConverter.ToUInt64(secondReservationKey, 0)), out scsiStatus); VerifyFieldInResponse("SCSIStatus", 0, scsiStatus); // Status code 0 indicates that the device has completed the task successfully. BaseTestSite.Log.Add(LogEntryKind.TestStep, "6. The second client sends Preempt service action of SCSI Persistent Reserve Out command by tunnel operation RSVD_TUNNEL_SCSI_OPERATION to server and expects success."); SendAndReceiveSCSICommand( secondClient, 10, CreateCDBBuffer_PersistentReserveOut(PERSISTENT_RESERVE_OUT_SERVICE_ACTION.PREEMPT, PERSISTENT_RESERVATION_SCOPE_AND_TYPE_CODE.WriteExclusiveRegistrantsOnly), CreateDataBuffer_PersistentReserveOut(System.BitConverter.ToUInt64(secondReservationKey, 0), System.BitConverter.ToUInt64(firstReservationkey, 0)), out scsiStatus); VerifyFieldInResponse("SCSIStatus", 0, scsiStatus); // Status code 0 indicates that the device has completed the task successfully. BaseTestSite.Log.Add(LogEntryKind.TestStep, "7. The first client closes the file."); client.CloseSharedVirtualDisk(); BaseTestSite.Log.Add(LogEntryKind.TestStep, "8. The second client closes the file."); secondClient.CloseSharedVirtualDisk(); }
public static Guid NewGuid() { byte[] bytes = new byte[16]; System.Random random = new System.Random(); random.NextBytes(bytes); return new Guid(bytes); }
public void Test() { System.Random r = new System.Random(); for(int i = 0; i < 1024; i++) { //Test ClassOf and SetClass: int c = r.Next(160); byte[] buf0 = new byte[Address.MemSize]; //Fill it with junk r.NextBytes(buf0); Address.SetClass(buf0, c); int c2 = Address.ClassOf(MemBlock.Reference(buf0, 0, Address.MemSize)); Assert.AreEqual(c,c2, "Class Round Trip"); //Test BigInteger stuff: int size = r.Next(1, MemSize + 1); byte[] buf1 = new byte[size]; r.NextBytes(buf1); BigInteger b1 = new BigInteger(buf1); byte[] buf2 = Address.ConvertToAddressBuffer(b1); //Check to see if the bytes are equivalent: int min_len = System.Math.Min(buf1.Length, buf2.Length); bool all_eq = true; for(int j = 0; j < min_len; j++) { all_eq = all_eq && (buf2[buf2.Length - j - 1] == buf1[buf1.Length - j - 1]); } if( !all_eq ) { System.Console.Error.WriteLine("Buf1: "); foreach(byte b in buf1) { System.Console.Write("{0} ",b); } System.Console.Error.WriteLine(); System.Console.Error.WriteLine("Buf2: "); foreach(byte b in buf2) { System.Console.Write("{0} ",b); } System.Console.Error.WriteLine(); } Assert.IsTrue(all_eq, "bytes are equivalent"); BigInteger b2 = new BigInteger(buf2); Assert.AreEqual(b1, b2, "BigInteger round trip"); } }