Skip to content

Commit f8bb9b6

Browse files
authored
Implement FixedTimeCompare for ImmutableArray<byte>
Added a new method to compare immutable byte arrays securely. Signed-off-by: Xen <lordofxen@deskasoft.com>
1 parent 4637e1d commit f8bb9b6

File tree

1 file changed

+17
-0
lines changed

1 file changed

+17
-0
lines changed

HashifyNet/Core/Utilities/HashComparer.cs

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,5 +80,22 @@ public static bool FixedTimeCompare(byte[] left, byte[] right)
8080
return accumulator == 0;
8181
#endif
8282
}
83+
84+
/// <summary>
85+
/// Compares two immutable byte arrays for equality in a way that is resistant to timing attacks.
86+
/// </summary>
87+
/// <remarks>This method performs a constant-time comparison to prevent timing attacks, which can occur when
88+
/// the time taken to compare two values leaks information about their contents. The method ensures that the
89+
/// comparison time depends only on the length of the immutable arrays, not their contents. <para> If the immutable arrays have different
90+
/// lengths, the method returns <see langword="false"/> immediately. </para></remarks>
91+
/// <param name="left">The first byte array to compare. Cannot be <see langword="null"/>.</param>
92+
/// <param name="right">The second byte array to compare. Cannot be <see langword="null"/>.</param>
93+
/// <returns><see langword="true"/> if the two immutable byte arrays are equal; otherwise, <see langword="false"/>.</returns>
94+
/// <exception cref="System.ArgumentNullException">Thrown if either <paramref name="left"/> or <paramref name="right"/> is <see langword="null"/>.</exception>
95+
public static bool FixedTimeCompare(ImmutableArray<byte> left, ImmutableArray<byte> right)
96+
{
97+
return FixedTimeCompare(left.ToArray(), right.ToArray());
98+
}
8399
}
84100
}
101+

0 commit comments

Comments
 (0)