Created
July 14, 2023 17:25
-
-
Save leandromoh/14c1615d9d21d3adfbd0961217e93433 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static string ToMd5(this string input) | |
{ | |
var inputBytes = Encoding.ASCII.GetBytes(input); | |
return inputBytes.ToMd5(0, inputBytes.Length); | |
} | |
public static string ToMd5(this byte[] inputBytes, int offset, int count) | |
{ | |
Span<char> chars = stackalloc char[32]; | |
inputBytes.ToMd5(offset, count, chars); | |
return chars.ToString(); | |
} | |
private static void ToMd5(this byte[] input, int offset, int count, Span<char> destination) | |
{ | |
using var md5 = MD5.Create(); | |
var hashBytes = md5.ComputeHash(input, offset, count); | |
var charsWritten = 0; | |
const string format = "X2"; | |
foreach (var hashByte in hashBytes) | |
{ | |
if (hashByte.TryFormat(destination, out charsWritten, format)) | |
{ | |
destination = destination.Slice(charsWritten); | |
} | |
else | |
{ | |
throw new InvalidOperationException( | |
$"byte '{hashByte}' could not be parsed using format '{format}' and avaible space of {destination.Length}"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment