private static async Task <IEnumerable <UmdDiscSector> > InternalMergePass(IEnumerable <UmdDiscSector> sectors) { UmdDiscSector?baseSector = null; var result = new List <UmdDiscSector>(); foreach (var sector in sectors.OrderBy(s => s.Crc32)) { //System.Console.WriteLine(sector.Crc32); if ((baseSector == null) || (baseSector.Crc32 != sector.Crc32)) { baseSector = sector; continue; } if ((baseSector.Crc32 == sector.Crc32) && (baseSector.Data != null) && (sector.Data != null)) { if (await BinaryComparer.Compare(baseSector.Data, 0, sector.Data, 0, UmdDisc.SectorSize)) { sector.Encoding = UmdEncoding.InternalLink; sector.Data = GetLinkData(baseSector.Id); sector.Length = (ushort)sector.Data.Length; } else { result.Add(sector); } } } return(result); }
public void TestSortable() { List <byte[]> all = new List <byte[]>(); all.Add(null); all.Add(Guid.Empty.ToByteArray()); for (int i = 0; i < 1000; i++) { all.Add(Guid.NewGuid().ToByteArray()); } all.Sort(new BinaryComparer()); byte[] last = null; Assert.IsNull(all[0]); all.RemoveAt(0); foreach (byte[] entry in all) { if (last != null) { Assert.IsTrue(StringComparer.Ordinal.Compare(Convert.ToBase64String(last), Convert.ToBase64String(entry)) < 0); } Assert.IsTrue(BinaryComparer.Compare(last, entry) < 0); } }
public bool IsRegionOverlap(RegionInfo other) { return(BinaryComparer.Equals(Namespace, other.Namespace) && BinaryComparer.Equals(Table, other.Table) && (other.StopKey?.Any() != true || BinaryComparer.Compare(StartKey, other.StopKey) < 0) && (StopKey?.Any() != true || BinaryComparer.Compare(StopKey, other.StartKey) > 0)); }
public ActionResult EditCredentials(EditCredentialsDTO request) { if (ModelState.IsValid) { if (request.CurrentPassword != request.NewPassword) { if (BinaryComparer.AreEqual(Account.Password, SHA512Hasher.Hash(request.CurrentPassword))) { PartnerBLL partnerBLL = new PartnerBLL(WebApp.Connector); Uri requestUrl = Request.Url; string baseUrl = new UriBuilder(requestUrl.Scheme, requestUrl.Host, requestUrl.Port).ToString(); partnerBLL.ChangePasswordEmailSubject = LocalizationProvider["ChangePasswordEmailSubject"]; partnerBLL.ChangePasswordEmailTemplate = LocalizationProvider["ChangePasswordEmailTemplate"]; partnerBLL.ChangePassword(Account, request.NewPassword, baseUrl); TempData["Result"] = "PasswordHasBeenChanged"; return(RedirectToAction("MyProfile")); } else { AddError("CurrentPassword", "CurrentPasswordDoesntMatch"); return(View()); } } else { AddError("NewPassword", "NewAndCurrentPasswordAreTheSame"); return(View()); } } else { return(BadRequestWithErrors()); } }
public void Compare_DifferentArraysOfSameLength_DifferencesAreReportedCorrectly (byte[] binary1, byte[] binary2, Difference[] differences) { var result = BinaryComparer.Compare(binary1, binary2); result.Should().BeOfType <BinariesHaveDifferences>() .Which.Differences.ShouldBeEquivalentTo(differences); }
public void Compare_ArrayAndItsCopy_AreSame() { var binary1 = new byte[] { 1, 5, 9, 0 }; var binary2 = binary1.ToArray(); var result = BinaryComparer.Compare(binary1, binary2); result.Should().BeOfType <BinariesAreEqual>(); }
public void Compare_TwoEmptyArrays_AreSame() { var binary1 = new byte[0]; var binary2 = new byte[0]; var result = BinaryComparer.Compare(binary1, binary2); result.Should().BeOfType <BinariesAreEqual>(); }
public void TestFromHexWithSpace() { const string hex = "01-0203-0405\t0607\r\n0809\r0a0b0c\n0d0e0f10 "; byte[] bin = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 }; Assert.AreEqual(0, BinaryComparer.Compare(bin, HexEncoding.DecodeBytes(hex))); Assert.AreEqual(0, BinaryComparer.Compare(bin, HexEncoding.DecodeBytes(Encoding.ASCII.GetBytes(hex)))); }
public void TestToFromHexPartial() { const string hex = "0102030405060708090a0b0c0d0e0f10"; byte[] bin = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 }; Assert.AreEqual(hex.Substring(4, 10), HexEncoding.EncodeBytes(bin, 2, 5)); Assert.AreEqual(0, BinaryComparer.Compare(new byte[] { 3, 4, 5, 6 }, HexEncoding.DecodeBytes(hex, 4, 8))); }
static void ExersizeFile(ManualResetEvent stop, TransactedCompoundFile file) { const int LIMIT = 512 * 512 / 4 - 512 * 3; Random r = new Random(); Dictionary <uint, byte[]> state = new Dictionary <uint, byte[]>(); while (true) { while (state.Count < 1000) { uint h = file.Create(); byte[] bytes = new byte[r.Next(5) == 0 ? r.Next(512) : r.Next(LIMIT)]; r.NextBytes(bytes); file.Write(h, bytes, 0, bytes.Length); state.Add(h, bytes); if (stop.WaitOne(0, false)) { return; } } foreach (var kv in state) { Assert.AreEqual(0, BinaryComparer.Compare(kv.Value, IOStream.ReadAllBytes(file.Read(kv.Key)))); if (stop.WaitOne(0, false)) { return; } } List <KeyValuePair <uint, byte[]> > capture = new List <KeyValuePair <uint, byte[]> >(state); for (int i = 0; i < capture.Count; i += r.Next(4)) { uint h = capture[i].Key; byte[] bytes = new byte[r.Next(512)]; r.NextBytes(bytes); file.Write(h, bytes, 0, bytes.Length); state[h] = bytes; Assert.AreEqual(0, BinaryComparer.Compare(bytes, IOStream.ReadAllBytes(file.Read(h)))); if (stop.WaitOne(0, false)) { return; } } for (int i = 0; i < capture.Count; i += 1 + r.Next(4)) { uint h = capture[i].Key; file.Delete(h); state.Remove(h); if (stop.WaitOne(0, false)) { return; } } } }
public void TestCompare() { Assert.AreEqual(0, BinaryComparer.Compare(null, null)); Assert.AreEqual(0, BinaryComparer.Compare(new byte[] { }, new byte[] { })); Assert.AreEqual(0, BinaryComparer.Compare(new byte[] { 1, 2, 3 }, new byte[] { 1, 2, 3 })); Assert.AreEqual(-1, BinaryComparer.Compare(null, new byte[] { 1, 2, 3 })); Assert.AreEqual(1, BinaryComparer.Compare(new byte[] { 1, 2, 3 }, null)); Assert.AreEqual(-1, BinaryComparer.Compare(new byte[] { 1, 2 }, new byte[] { 1, 2, 3 })); Assert.AreEqual(1, BinaryComparer.Compare(new byte[] { 1, 2, 3 }, new byte[] { 1, 2 })); }
public void TestHashCode() { Assert.AreEqual(0, BinaryComparer.GetHashCode(null)); Assert.AreEqual(0, BinaryComparer.GetHashCode(new byte[] { })); Assert.AreEqual(BinaryComparer.GetHashCode(new byte[] { 1, 2, 3 }), BinaryComparer.GetHashCode(new byte[] { 1, 2, 3 })); Assert.AreNotEqual(BinaryComparer.GetHashCode(null), BinaryComparer.GetHashCode(new byte[] { 1, 2, 3 })); Assert.AreNotEqual(BinaryComparer.GetHashCode(new byte[] { 1, 2, 3 }), BinaryComparer.GetHashCode(null)); Assert.AreNotEqual(BinaryComparer.GetHashCode(new byte[] { 1, 2 }), BinaryComparer.GetHashCode(new byte[] { 1, 2, 3 })); Assert.AreNotEqual(BinaryComparer.GetHashCode(new byte[] { 1, 2, 3 }), BinaryComparer.GetHashCode(new byte[] { 1, 2 })); }
public void TestEquals() { Assert.IsTrue(BinaryComparer.Equals(null, null)); Assert.IsTrue(BinaryComparer.Equals(new byte[] { }, new byte[] { })); Assert.IsTrue(BinaryComparer.Equals(new byte[] { 1, 2, 3 }, new byte[] { 1, 2, 3 })); Assert.IsFalse(BinaryComparer.Equals(null, new byte[] { 1, 2, 3 })); Assert.IsFalse(BinaryComparer.Equals(new byte[] { 1, 2, 3 }, null)); Assert.IsFalse(BinaryComparer.Equals(new byte[] { 1, 2 }, new byte[] { 1, 2, 3 })); Assert.IsFalse(BinaryComparer.Equals(new byte[] { 1, 2, 3 }, new byte[] { 1, 2 })); }
// TODO: expand comparer to use CompareFlags flags public async Task <List <CdromSectorComparisonResult> > Compare(CdromImage image1, CdromImage image2) { var result = new List <CdromSectorComparisonResult>(); var sectorMax = Math.Max(image1.Sectors.Count, image2.Sectors.Count); for (var i = 0; i < sectorMax; i++) { if (i >= image1.Sectors.Count) { result.Add(new CdromSectorComparisonResult { SectorPhysicalAddress = i, Message = "Sectors is missing in first image", Equal = false }); continue; } if (i >= image2.Sectors.Count) { result.Add(new CdromSectorComparisonResult { SectorPhysicalAddress = i, Message = "Sectors is missing in second image", Equal = false }); continue; } if (await BinaryComparer.Compare(image1.Sectors[i].Data, 0, image2.Sectors[i].Data, 0, CdromConstants.SectorDataSize)) { result.Add(new CdromSectorComparisonResult { SectorPhysicalAddress = i, Message = "Sectors are equal", Equal = true }); } else { result.Add(new CdromSectorComparisonResult { SectorPhysicalAddress = i, Message = "Sectors are not equal", Equal = false }); } } return(result); }
// TODO: optimize this method public static async Task Merge(UmdDisc masterDisc, UmdDisc disc) { var masterSectors = masterDisc.Sectors.Where(s => s.Encoding == UmdEncoding.None).OrderBy(s => s.Crc32).ToList(); var sectors = disc.Sectors.Where(s => s.Encoding == UmdEncoding.None).OrderBy(s => s.Crc32).ToList(); // if nothing to compare return if ((masterSectors == null) || (sectors == null) || (!masterSectors.Any()) || (!sectors.Any())) { return; } int masterCursor = 0, cursor = 0; // sync cursors while ((masterCursor < masterSectors.Count) && (cursor < sectors.Count)) { if (masterSectors[masterCursor].Crc32 == sectors[cursor].Crc32) { int subCursor = 0; while ((masterCursor + subCursor < masterSectors.Count) && (masterSectors[masterCursor].Crc32 == masterSectors[masterCursor + subCursor].Crc32)) { if ((masterSectors[masterCursor + subCursor].Data != null) && (sectors[cursor].Data != null) && (await BinaryComparer.Compare(masterSectors[masterCursor + subCursor].Data, 0, sectors[cursor].Data, 0, UmdDisc.SectorSize))) { sectors[cursor].Encoding = UmdEncoding.ExternalLink; sectors[cursor].Data = GetLinkData(masterSectors[masterCursor + subCursor].Id); sectors[cursor].Length = 4; sectors[cursor].Crc32 = Crc32Algorithm.Compute(sectors[cursor].Data, 0, 4); break; } subCursor++; } cursor++; continue; } if (masterSectors[masterCursor].Crc32 < sectors[cursor].Crc32) { masterCursor++; continue; } if (masterSectors[masterCursor].Crc32 > sectors[cursor].Crc32) { cursor++; continue; } } }
public void TestToFromHex() { byte[] all = new byte[256]; for (int i = 0; i < all.Length; i++) { all[i] = (byte)i; } Assert.AreEqual(AllHex, HexEncoding.EncodeBytes(all)); Assert.AreEqual(0, BinaryComparer.Compare(all, HexEncoding.DecodeBytes(AllHex))); Assert.AreEqual(0, BinaryComparer.Compare(all, HexEncoding.DecodeBytes(AllHex.ToUpper()))); }
public void TestSafe64EncodingLargeArray() { Random rand = new Random(); byte[] data = new byte[0x400000]; rand.NextBytes(data); string testAsc = Safe64Encoding.EncodeBytes(data); Assert.AreEqual(0, BinaryComparer.Compare(data, Safe64Encoding.DecodeBytes(testAsc))); testAsc = AsciiEncoder.EncodeBytes(data); Assert.AreEqual(0, BinaryComparer.Compare(data, AsciiEncoder.DecodeBytes(testAsc))); }
void TestEncryptDecrypt(SymmetricAlgorithm ealg, SymmetricAlgorithm dalg) { System.Diagnostics.Trace.WriteLine(String.Format("b={0}, k={1}, r={2}", ealg.BlockSize, ealg.KeySize, ealg is ModifiedRijndael ? ((ModifiedRijndael)ealg).Rounds : ((ModifiedRijndael)dalg).Rounds)); byte[] test = Encoding.ASCII.GetBytes("Testing 123"); byte[] copy; using (ICryptoTransform enc = ealg.CreateEncryptor()) copy = enc.TransformFinalBlock(test, 0, test.Length); using (ICryptoTransform dec = dalg.CreateDecryptor()) copy = dec.TransformFinalBlock(copy, 0, copy.Length); Assert.AreEqual(0, BinaryComparer.Compare(test, copy)); }
private void TestAes256CBC(bool enc, string key, string iv, string input, string expect) { ModifiedRijndael r = ModifiedRijndael.Create(); r.Mode = CipherMode.CBC; r.Padding = PaddingMode.None; r.BlockSize = iv.Length / 2 * 8; r.IV = HexEncoding.DecodeBytes(iv); r.KeySize = key.Length / 2 * 8; r.Key = HexEncoding.DecodeBytes(key); ICryptoTransform xf = enc ? r.CreateEncryptor() : r.CreateDecryptor(); byte[] result = xf.TransformFinalBlock(HexEncoding.DecodeBytes(input), 0, input.Length / 2); byte[] test = HexEncoding.DecodeBytes(expect); Assert.AreEqual(0, BinaryComparer.Compare(test, result)); }
public void BinaryComparer_ShouldReturn_SameSizesAndIdenticalBinaries() { var binaryComparer = new BinaryComparer(); //var var leftBinary = new byte[15]; new Random().NextBytes(leftBinary); var rightBinary = leftBinary; var actualResult = binaryComparer.Compare(leftBinary, rightBinary); var expectedResult = new Tuple <BinaryComparerEnum, List <DiffOffset> >(BinaryComparerEnum.IdenticalBinary, new List <DiffOffset>()); Assert.AreEqual(actualResult.Item1, expectedResult.Item1); CollectionAssert.AreEquivalent(expectedResult.Item2.ToSimpleList(), actualResult.Item2.ToSimpleList()); }
void TestEncoderAgainstBase64(int repeat, int size) { Random rand = new Random(); byte[] data = new byte[size]; while (repeat-- > 0) { rand.NextBytes(data); string testB64 = Convert.ToBase64String(data); string testAsc = Safe64Encoding.EncodeBytes(data); Assert.AreEqual(testB64.Replace('+', '-').Replace('/', '_').Replace("=", ""), testAsc); Assert.AreEqual(0, BinaryComparer.Compare(data, Safe64Encoding.DecodeBytes(testAsc))); Assert.AreEqual(0, BinaryComparer.Compare(data, AsciiEncoder.DecodeBytes(testAsc))); } }
public static void AssertEquals(IDictionary <Guid, TestInfo> x, IEnumerable <KeyValuePair <Guid, TestInfo> > y) { Dictionary <Guid, TestInfo> copy = new Dictionary <Guid, TestInfo>(x); foreach (KeyValuePair <Guid, TestInfo> item in y) { TestInfo value; Assert.IsTrue(x.TryGetValue(item.Key, out value)); Assert.AreEqual(item.Key, item.Value.MyKey); Assert.AreEqual(item.Value.MyKey, value.MyKey); Assert.AreEqual(item.Value.SetNumber, value.SetNumber); Assert.AreEqual(item.Value.CreateOrder, value.CreateOrder); Assert.IsTrue(BinaryComparer.Equals(item.Value.RandomBytes, value.RandomBytes)); Assert.IsTrue(copy.Remove(item.Key)); } Assert.IsEmpty(copy); }
private RegionInfo GetInfoFromCache(byte[] table, byte[] key) { if (BinaryComparer.Compare(table, _metaTableName) == 0) { return(_metaRegionInfo); } var search = RegionInfo.CreateRegionSearchKey(table, key); var info = _cache.GetInfo(search); if (info == null || false == BinaryComparer.Equals(table, info.Table)) { return(null); } if (info.StopKey.Length > 0 && BinaryComparer.Compare(key, info.StopKey) >= 0) { return(null); } return(info); }
public void TestEncryptDecryptStream() { byte[] result; byte[] data = new byte[ushort.MaxValue]; Random rand = new Random(); rand.NextBytes(data); using (MemoryStream final = new MemoryStream()) using (MemoryStream ms = new MemoryStream()) { using (Stream e = Encryptor.Encrypt(new NonClosingStream(ms))) { for (int i = 0; i < data.Length;) { int count = Math.Max(i + 1, Math.Min(data.Length, i + 1 + rand.Next(2000))); e.Write(data, i, count - i); i = count; } e.Flush(); } using (Stream d = Encryptor.Decrypt(new MemoryStream(ms.ToArray()))) { for (int i = 0; i < data.Length;) { int count = Math.Max(i + 1, Math.Min(data.Length, i + 1 + rand.Next(2000))); byte[] tmp = IOStream.Read(d, count - i); final.Write(tmp, 0, tmp.Length); i = count; } } result = final.ToArray(); } Assert.AreEqual(data.Length, result.Length); Assert.IsTrue(BinaryComparer.Equals(data, result)); }
public void BinaryComparer_ShouldReturn_SameSizesAndDifferentBinaries() { var binaryComparer = new BinaryComparer(); var leftBinary = new byte[15] { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 }; var rightBinary = new byte[15] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1 }; var actualResult = binaryComparer.Compare(leftBinary, rightBinary); var expectedResult = new Tuple <BinaryComparerEnum, List <DiffOffset> >(BinaryComparerEnum.EqualSize, new List <DiffOffset>() { new DiffOffset { StartIndex = 0, Length = 15 } } ); Assert.AreEqual(actualResult.Item1, expectedResult.Item1); CollectionAssert.AreEquivalent(expectedResult.Item2.ToSimpleList(), actualResult.Item2.ToSimpleList()); }
private void AssertCompare(BinaryComparer comparer, int expected, string v1, string v2) { Assert.Equal(expected, comparer.Compare(Encoding.UTF8.GetBytes(v1), Encoding.UTF8.GetBytes(v2))); }
public void Compare_WithNullArgument_ThrowsArgumentNullException() { Assert.Throws <ArgumentNullException>(() => BinaryComparer.Compare(null, new byte[1])); Assert.Throws <ArgumentNullException>(() => BinaryComparer.Compare(new byte[2], null)); }
private void AssertCompare(BinaryComparer comparer, int expected, string v1, string v2) { Assert.AreEqual(expected, comparer.Compare(Encoding.UTF8.GetBytes(v1), Encoding.UTF8.GetBytes(v2)), string.Format("{0} -> {1}", v1, v2)); }
public void Compare_ArraysOfDifferentLength_ReportedAsOfDifferentSize(byte[] binary1, byte[] binary2) { var result = BinaryComparer.Compare(binary1, binary2); result.Should().BeOfType <BinariesOfDifferentSize>(); }
public LoginResult Login(PartnerCredentialDTO credential, IPAddress ipAddress, bool keepOpened, out PartnerSessionDTO session) { Connector.IsTransaction = true; PartnerBLL partnerBLL = new PartnerBLL(Connector); PartnerDTO partner = partnerBLL.ReadByUsername(credential.Username); if (partner != null) { if (!partner.IsLocked) { byte[] credentialPassword = SHA512Hasher.Hash(credential.Password); if (BinaryComparer.AreEqual(credentialPassword, partner.Password)) { if (partner.HasEmailAddressBeenVerified) { DateTime loggedAt = DateTime.UtcNow; session = new PartnerSessionDTO() { Partner = partner, IPAddress = ipAddress, LoggedAt = loggedAt }; if (!keepOpened) { session.ExpiresOn = loggedAt.AddMinutes(16); } Create(session); Connector.CommitTransaction(); return(LoginResult.OK); } else { Connector.RollbackTransaction(); session = null; return(LoginResult.EmailAddressHasNotBeenVerified); } } else { PartnerLoginAttemptBLL loginAttemptBLL = new PartnerLoginAttemptBLL(Connector); PartnerLoginAttemptDTO loginAttempt = new PartnerLoginAttemptDTO() { Partner = partner, IPAddress = ipAddress }; loginAttemptBLL.Create(loginAttempt); Guid partnerId = partner.Id; PartnerSessionDTO lastSession = ReadLastByPartner(partnerId); List <PartnerLoginAttemptDTO> loginAttempts = loginAttemptBLL.ReadByPartnerAndTimeStampAsDate(partnerId, lastSession?.LoggedAt ?? DateTime.UtcNow.Date).ToList(); if (loginAttempts.Count >= 3) { partnerBLL.Update(partnerId, new Dictionary <string, object>() { { "IsLocked", true } }); } Connector.CommitTransaction(); session = null; return(LoginResult.PasswordDoesntMatch); } } else { Connector.RollbackTransaction(); session = null; return(LoginResult.AccountIsLocked); } } else { Connector.RollbackTransaction(); session = null; return(LoginResult.AccountDoesntExist); } }