diff --git a/Common.Tests/Utils/HashingUtilsTests.cs b/Common.Tests/Utils/HashingUtilsTests.cs index a59da197..71dd091d 100644 --- a/Common.Tests/Utils/HashingUtilsTests.cs +++ b/Common.Tests/Utils/HashingUtilsTests.cs @@ -6,6 +6,7 @@ public class HashingUtilsTests { [Test] [Arguments("test", "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08")] + [Arguments("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in", "2fac5f5f1d048a84fbb75c389f4596e05023ac17da4fcf45a5954d2d9a394301")] public async Task HashSha256(string str, string expectedHash) { // Act diff --git a/Common/Utils/HashingUtils.cs b/Common/Utils/HashingUtils.cs index 4181ebd9..64605ee7 100644 --- a/Common/Utils/HashingUtils.cs +++ b/Common/Utils/HashingUtils.cs @@ -1,4 +1,5 @@ -using System.Security.Cryptography; +using System.Buffers; +using System.Security.Cryptography; using System.Text; namespace OpenShock.Common.Utils; @@ -12,8 +13,33 @@ public static class HashingUtils /// public static string HashSha256(string str) { - Span tempSpan = stackalloc byte[32]; - SHA256.HashData(Encoding.UTF8.GetBytes(str), tempSpan); - return Convert.ToHexStringLower(tempSpan); + Span hashDigest = stackalloc byte[SHA256.HashSizeInBytes]; + + const int maxStackSize = 256; // Threshold for stack allocation + int byteCount = Encoding.UTF8.GetByteCount(str); + + if (byteCount > maxStackSize) + { + byte[] decodedBytes = ArrayPool.Shared.Rent(byteCount); + + try + { + int decodedCount = Encoding.UTF8.GetBytes(str, decodedBytes); + SHA256.HashData(decodedBytes.AsSpan(0, decodedCount), hashDigest); + } + finally + { + ArrayPool.Shared.Return(decodedBytes, true); + } + } + else + { + Span decodedBytes = stackalloc byte[maxStackSize]; + int decodedCount = Encoding.UTF8.GetBytes(str, decodedBytes); + SHA256.HashData(decodedBytes[..decodedCount], hashDigest); + } + + + return Convert.ToHexStringLower(hashDigest); } }