From a7c4b65a99d8e12aaa6a76ae7306e1e43c4cdf10 Mon Sep 17 00:00:00 2001 From: Westin Musser <127992899+westin-m@users.noreply.github.com> Date: Wed, 9 Oct 2024 17:32:59 -0700 Subject: [PATCH] Use FixedTimeEquals in NETCore targets (#2857) * use fixedtimeequals * apply change to span version * Apply NoOptimization --- src/Microsoft.IdentityModel.Tokens/Utility.cs | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/src/Microsoft.IdentityModel.Tokens/Utility.cs b/src/Microsoft.IdentityModel.Tokens/Utility.cs index 4990981417..e064389741 100644 --- a/src/Microsoft.IdentityModel.Tokens/Utility.cs +++ b/src/Microsoft.IdentityModel.Tokens/Utility.cs @@ -133,7 +133,7 @@ public static bool IsHttps(Uri uri) /// /// true if the bytes are equal, false otherwise. /// - [MethodImpl(MethodImplOptions.NoInlining)] + [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] public static bool AreEqual(byte[] a, byte[] b) { ReadOnlySpan a1, a2; @@ -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 } /// @@ -174,7 +177,7 @@ public static bool AreEqual(byte[] a, byte[] b) /// /// true if the bytes are equal, false otherwise. /// - [MethodImpl(MethodImplOptions.NoInlining)] + [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] internal static bool AreEqual(ReadOnlySpan a, ReadOnlySpan b, int length) { if ((a.Length < length || b.Length < length)) @@ -189,13 +192,16 @@ internal static bool AreEqual(ReadOnlySpan a, ReadOnlySpan 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)