public void BasicTests() { // Make sure byte array comparison works within hashset and that the underlying API won't pull the floor out. var byteArray = new byte[] { 1, 2, 3 }; var sameByteArray = new byte[] { 1, 2, 3 }; var differentByteArray = new byte[] { 4, 5, 6 }; var twoSet = new HashSet <byte[]>(new ByteArrayEqualityComparer()) { byteArray, sameByteArray, differentByteArray }; Assert.True(ByteHelpers.CompareFastUnsafe(byteArray, sameByteArray)); Assert.False(ByteHelpers.CompareFastUnsafe(byteArray, differentByteArray)); Assert.Equal(2, twoSet.Count); // It's probabilistically ensured that it never produces the same scalar, so unit test should pass always. var pseudoSet = new HashSet <byte[]>(); var secureSet = new HashSet <byte[]>(); var count = 100; using var insecureRandom = new InsecureRandom(); using var secureRandom = new SecureRandom(); for (int i = 0; i < count; i++) { pseudoSet.Add(insecureRandom.GetBytes(10)); secureSet.Add(secureRandom.GetBytes(10)); } Assert.Equal(count, pseudoSet.Count); Assert.Equal(count, secureSet.Count); }
private async Task <(bool same, byte[] hash)> WorkWithHashAsync(ByteArrayBuilder byteArrayBuilder, CancellationToken cancellationToken) { byte[] hash = null; try { var bytes = byteArrayBuilder.ToArray(); hash = HashHelpers.GenerateSha256Hash(bytes); if (File.Exists(DigestFilePath)) { var digest = await File.ReadAllBytesAsync(DigestFilePath, cancellationToken).ConfigureAwait(false); if (ByteHelpers.CompareFastUnsafe(hash, digest)) { if (File.Exists(NewFilePath)) { File.Delete(NewFilePath); } return(true, hash); } } } catch (Exception ex) { Logger.LogWarning("Failed to read digest."); Logger.LogInfo(ex); } return(false, hash); }
public static bool CheckExpectedHash(string filePath, string sourceFolderPath) { var fileHash = GetHashFile(filePath); try { var digests = File.ReadAllLines(Path.Combine(sourceFolderPath, "digests.txt")); foreach (var digest in digests) { var expectedHash = ByteHelpers.FromHex(digest); if (ByteHelpers.CompareFastUnsafe(fileHash, expectedHash)) { return(true); } } return(false); } catch { return(false); } }
public static bool operator ==(ByteArraySerializableBase x, byte[] y) => ByteHelpers.CompareFastUnsafe(x?.ToBytes(), y);
public static bool operator ==(byte[] x, ByteArraySerializableBase y) => ByteHelpers.CompareFastUnsafe(x, y?.ToBytes());
public bool Equals(byte[] other) => ByteHelpers.CompareFastUnsafe(ToBytes(), other);
public bool Equals([AllowNull] byte[] x, [AllowNull] byte[] y) => ByteHelpers.CompareFastUnsafe(x, y);