From 834e1f702bf33e3ba8677912f7a29730acb817aa Mon Sep 17 00:00:00 2001 From: Stephen Toub Date: Wed, 26 Jul 2023 13:19:33 -0400 Subject: [PATCH] Use one-shot hash APIs in a couple of places (#2159) --- .../SignedHttpRequestHandler.cs | 11 +++++++++-- src/Microsoft.IdentityModel.Tokens/Utility.cs | 8 +++++++- 2 files changed, 16 insertions(+), 3 deletions(-) diff --git a/src/Microsoft.IdentityModel.Protocols.SignedHttpRequest/SignedHttpRequestHandler.cs b/src/Microsoft.IdentityModel.Protocols.SignedHttpRequest/SignedHttpRequestHandler.cs index 5f5a4962ff..768268b16d 100644 --- a/src/Microsoft.IdentityModel.Protocols.SignedHttpRequest/SignedHttpRequestHandler.cs +++ b/src/Microsoft.IdentityModel.Protocols.SignedHttpRequest/SignedHttpRequestHandler.cs @@ -1213,11 +1213,18 @@ private static string CalculateBase64UrlEncodedHash(string data) private static string CalculateBase64UrlEncodedHash(byte[] bytes) { + byte[] hashedBytes; + +#if NET6_0_OR_GREATER + hashedBytes = SHA256.HashData(bytes); +#else using (var hash = SHA256.Create()) { - var hashedBytes = hash.ComputeHash(bytes); - return Base64UrlEncoder.Encode(hashedBytes); + hashedBytes = hash.ComputeHash(bytes); } +#endif + + return Base64UrlEncoder.Encode(hashedBytes); } /// diff --git a/src/Microsoft.IdentityModel.Tokens/Utility.cs b/src/Microsoft.IdentityModel.Tokens/Utility.cs index b9f53cf9b8..1723a5a34d 100644 --- a/src/Microsoft.IdentityModel.Tokens/Utility.cs +++ b/src/Microsoft.IdentityModel.Tokens/Utility.cs @@ -251,10 +251,16 @@ internal static void Zero(byte[] byteArray) internal static byte[] GenerateSha256Hash(string input) { + byte[] bytes = Encoding.UTF8.GetBytes(input); + +#if NET6_0_OR_GREATER + return SHA256.HashData(bytes); +#else using (var hash = SHA256.Create()) { - return hash.ComputeHash(Encoding.UTF8.GetBytes(input)); + return hash.ComputeHash(bytes); } +#endif } } }