Skip to content

Commit

Permalink
Use FixedTimeEquals in NETCore targets (#2857)
Browse files Browse the repository at this point in the history
* use fixedtimeequals

* apply change to span version

* Apply NoOptimization
  • Loading branch information
westin-m authored Oct 10, 2024
1 parent 41b63fa commit a7c4b65
Showing 1 changed file with 10 additions and 4 deletions.
14 changes: 10 additions & 4 deletions src/Microsoft.IdentityModel.Tokens/Utility.cs
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ public static bool IsHttps(Uri uri)
/// <returns>
/// true if the bytes are equal, false otherwise.
/// </returns>
[MethodImpl(MethodImplOptions.NoInlining)]
[MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)]
public static bool AreEqual(byte[] a, byte[] b)
{
ReadOnlySpan<byte> a1, a2;
Expand All @@ -151,13 +151,16 @@ public static bool AreEqual(byte[] a, byte[] b)
a2 = b.AsSpan();
}

#if NETCOREAPP
return System.Security.Cryptography.CryptographicOperations.FixedTimeEquals(a1, a2);
#else
int result = 0;
for (int i = 0; i < a1.Length; i++)
{
result |= a1[i] ^ a2[i];
}

return result == 0;
#endif
}

/// <summary>
Expand All @@ -174,7 +177,7 @@ public static bool AreEqual(byte[] a, byte[] b)
/// <returns>
/// true if the bytes are equal, false otherwise.
/// </returns>
[MethodImpl(MethodImplOptions.NoInlining)]
[MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)]
internal static bool AreEqual(ReadOnlySpan<byte> a, ReadOnlySpan<byte> b, int length)
{
if ((a.Length < length || b.Length < length))
Expand All @@ -189,13 +192,16 @@ internal static bool AreEqual(ReadOnlySpan<byte> a, ReadOnlySpan<byte> b, int le
b = b.Slice(0, length);
}

#if NETCOREAPP
return System.Security.Cryptography.CryptographicOperations.FixedTimeEquals(a, b);
#else
int result = 0;
for (int i = 0; i < a.Length; i++)
{
result |= a[i] ^ b[i];
}

return result == 0;
#endif
}

internal static byte[] ConvertToBigEndian(long i)
Expand Down

0 comments on commit a7c4b65

Please sign in to comment.