@@ -19,38 +19,24 @@ public static class HashingUtils
1919 private static readonly VerifyHashResult VerifyHashFailureResult = new ( false , false ) ;
2020
2121 /// <summary>
22- /// Hashes string using SHA-256 and returns the result as a uppercase string
22+ /// Hashes string using SHA-256 and returns the result as a lowercase string
2323 /// </summary>
2424 /// <param name="str"></param>
2525 /// <returns></returns>
2626 public static string HashSha256 ( string str )
2727 {
2828 Span < byte > hashDigest = stackalloc byte [ SHA256 . HashSizeInBytes ] ;
2929
30- const int maxStackSize = 256 ; // Threshold for stack allocation
31- int byteCount = Encoding . UTF8 . GetByteCount ( str ) ;
30+ var nAlloc = str . Length <= 512
31+ ? Encoding . UTF8 . GetMaxByteCount ( str . Length )
32+ : Encoding . UTF8 . GetByteCount ( str ) ;
33+ var buffer = nAlloc <= 256
34+ ? stackalloc byte [ nAlloc ]
35+ : new byte [ nAlloc ] ;
3236
33- if ( byteCount > maxStackSize )
34- {
35- byte [ ] decodedBytes = ArrayPool < byte > . Shared . Rent ( byteCount ) ;
36-
37- try
38- {
39- int decodedCount = Encoding . UTF8 . GetBytes ( str , decodedBytes ) ;
40- SHA256 . HashData ( decodedBytes . AsSpan ( 0 , decodedCount ) , hashDigest ) ;
41- }
42- finally
43- {
44- ArrayPool < byte > . Shared . Return ( decodedBytes , true ) ;
45- }
46- }
47- else
48- {
49- Span < byte > decodedBytes = stackalloc byte [ maxStackSize ] ;
50- int decodedCount = Encoding . UTF8 . GetBytes ( str , decodedBytes ) ;
51- SHA256 . HashData ( decodedBytes [ ..decodedCount ] , hashDigest ) ;
52- }
37+ var byteCount = Encoding . UTF8 . GetBytes ( str , buffer ) ;
5338
39+ SHA256 . HashData ( buffer [ ..byteCount ] , hashDigest ) ;
5440
5541 return Convert . ToHexStringLower ( hashDigest ) ;
5642 }
0 commit comments