Skip to content

Commit

Permalink
Add more MD5 methods and Compute136
Browse files Browse the repository at this point in the history
  • Loading branch information
BigBang1112 committed Dec 8, 2024
1 parent c435869 commit 3eb67a0
Showing 1 changed file with 64 additions and 0 deletions.
64 changes: 64 additions & 0 deletions Src/GBX.NET.Crypto/MD5.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,18 @@ public static byte[] Compute(byte[] data)
#endif
}

#if NET6_0_OR_GREATER
public static byte[] Compute(Span<byte> data)
{
return System.Security.Cryptography.MD5.HashData(data);
}

public static int Compute(Span<byte> data, Span<byte> destination)
{
return System.Security.Cryptography.MD5.HashData(data, destination);
}
#endif

public static byte[] Compute(string data)
{
return Compute(Encoding.ASCII.GetBytes(data));
Expand Down Expand Up @@ -42,4 +54,56 @@ public static async Task<byte[]> ComputeAsync(string data, CancellationToken can
{
return await ComputeAsync(Encoding.ASCII.GetBytes(data), cancellationToken);
}

public static string Compute136(string text)
{
#if NET6_0_OR_GREATER
var charSpan = text.AsSpan();
Span<char> loweredCharSpan = stackalloc char[text.Length];
if (charSpan.ToLowerInvariant(loweredCharSpan) != text.Length)
{
loweredCharSpan = text.ToLowerInvariant().ToArray();
}
Span<byte> bytes = stackalloc byte[text.Length * 2];
if (Encoding.UTF8.GetBytes(loweredCharSpan, bytes) != bytes.Length)
{
bytes = Encoding.UTF8.GetBytes(text.ToLowerInvariant());
}
Span<byte> hash = stackalloc byte[17];
if (Compute(bytes, hash.Slice(1)) != 16)
{
throw new InvalidOperationException();
}
#else
var lowered = text.ToLower();
var bytes = Encoding.UTF8.GetBytes(lowered);
var hashWithoutLength = Compute(bytes);
var hash = new byte[17];
Buffer.BlockCopy(hashWithoutLength, 0, hash, 1, hashWithoutLength.Length);
#endif
hash[0] = (byte)bytes.Length;

return ToHex(hash).ToString();
}

private static Span<char> ToHex(Span<byte> value)
{
var str = new char[value.Length * 2];

for (var i = 0; i < value.Length; i++)
{
var hex1 = HexIntToChar((byte)(value[i] % 16));
var hex2 = HexIntToChar((byte)(value[i] / 16));

str[i * 2] = hex1;
str[i * 2 + 1] = hex2;
}

return str;
}

private static char HexIntToChar(byte v)
{
return v < 10 ? (char)(v + 48) : (char)(v + 55);
}
}

0 comments on commit 3eb67a0

Please sign in to comment.