Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Optimize Sha256 hasher #152

Merged
merged 1 commit into from
Jan 29, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Common.Tests/Utils/HashingUtilsTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
34 changes: 30 additions & 4 deletions Common/Utils/HashingUtils.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.Security.Cryptography;
using System.Buffers;
using System.Security.Cryptography;
using System.Text;

namespace OpenShock.Common.Utils;
Expand All @@ -12,8 +13,33 @@ public static class HashingUtils
/// <returns></returns>
public static string HashSha256(string str)
{
Span<byte> tempSpan = stackalloc byte[32];
SHA256.HashData(Encoding.UTF8.GetBytes(str), tempSpan);
return Convert.ToHexStringLower(tempSpan);
Span<byte> 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<byte>.Shared.Rent(byteCount);

try
{
int decodedCount = Encoding.UTF8.GetBytes(str, decodedBytes);
SHA256.HashData(decodedBytes.AsSpan(0, decodedCount), hashDigest);
}
finally
{
ArrayPool<byte>.Shared.Return(decodedBytes, true);
}
}
else
{
Span<byte> decodedBytes = stackalloc byte[maxStackSize];
int decodedCount = Encoding.UTF8.GetBytes(str, decodedBytes);
SHA256.HashData(decodedBytes[..decodedCount], hashDigest);
}


return Convert.ToHexStringLower(hashDigest);
}
}