diff --git a/framework/Furion/DataEncryption/MD5Encryption.cs b/framework/Furion/DataEncryption/MD5Encryption.cs index b3fd28eb79724ed50151fb2e028bf48487f7e80c..fbfcfc14426680f631348397b2ef680624858891 100644 --- a/framework/Furion/DataEncryption/MD5Encryption.cs +++ b/framework/Furion/DataEncryption/MD5Encryption.cs @@ -1,6 +1,6 @@ using Furion.DependencyInjection; using System; -using System.Runtime.CompilerServices; +using System.Reflection; using System.Security.Cryptography; using System.Text; @@ -10,9 +10,24 @@ namespace Furion.DataEncryption /// MD5 加密 /// [SkipScan] - public class MD5Encryption + public static unsafe class MD5Encryption { - private static readonly char[] Digitals = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; + private const uint LOWERCASING = 0x2020U; + + private static readonly delegate* managed, Span, uint, void> _EncodeToUtf16Ptr; + + [ThreadStatic] + private static MD5 instance; + + /// + /// MD5实例 + /// + public static MD5 Instance => instance ??= MD5.Create(); + + static MD5Encryption() + { + _EncodeToUtf16Ptr = (delegate* managed, Span, uint, void>)typeof(uint).Assembly.GetType("System.HexConverter").GetMethod("EncodeToUtf16", BindingFlags.Static | BindingFlags.Public).MethodHandle.GetFunctionPointer(); + } /// /// 字符串 MD5 比较 @@ -33,51 +48,13 @@ namespace Furion.DataEncryption /// public static string Encrypt(string text) { - var bytes = Encoding.UTF8.GetBytes(text); - - return ByteToString(MD5Instances.Instance.ComputeHash(bytes)); - } - - /// - /// 创建MD5实例 - /// - private static class MD5Instances - { - /// - /// 线程静态变量 - /// - [ThreadStatic] - private static MD5 instance; - - /// - /// MD5实例 - /// - public static MD5 Instance => instance ?? Create(); - - [MethodImpl(MethodImplOptions.NoInlining)] - private static MD5 Create() - { - instance = MD5.Create() ?? Activator.CreateInstance(); - - return instance; - } - } - - /// - /// 重写ToString方法 - /// - /// - /// - private static string ByteToString(byte[] bytes) - { - var chars = new char[bytes.Length * 2]; - var index = 0; - foreach (var item in bytes) + return string.Create(32, text, static (p, q) => { - chars[index] = Digitals[item >> 4]; ++index; - chars[index] = Digitals[item & 15]; ++index; - } - return new string(chars, 0, chars.Length); + byte[] buffer = Encoding.UTF8.GetBytes(q); + Span signed = stackalloc byte[16]; + Instance.TryComputeHash(buffer, signed, out _); + _EncodeToUtf16Ptr(signed, p, LOWERCASING); + }); } } } \ No newline at end of file diff --git a/framework/Furion/Furion.csproj b/framework/Furion/Furion.csproj index 4cfd674a0756b7632357ac4adf1d458d7a0ade02..394b6419809241f5268df653ec54b994026c30f9 100644 --- a/framework/Furion/Furion.csproj +++ b/framework/Furion/Furion.csproj @@ -4,6 +4,7 @@ net5.0 1.11.1 让 .NET 开发更简单,更通用,更流行。 + true