Calculate a MD5 hash from a string

后端 未结 16 2133
独厮守ぢ
独厮守ぢ 2020-11-28 21:06

I use the following C# code to calculate a MD5 hash from a string. It works well and generates a 32-character hex string like this: 900150983cd24fb0d6963f7d28e17f72

16条回答
  •  囚心锁ツ
    2020-11-28 21:54

    A faster alternative of existing answer for .NET Core 2.1 and higher:

    public static string CreateMD5(string s)
    {
        using (System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create())
        {
            var encoding = Encoding.ASCII;
            var data = encoding.GetBytes(s);
    
            Span hashBytes = stackalloc byte[16];
            md5.TryComputeHash(data, hashBytes, out int written);
            if(written != hashBytes.Length)
                throw new OverflowException();
    
    
            Span stringBuffer = stackalloc char[32];
            for (int i = 0; i < hashBytes.Length; i++)
            {
                hashBytes[i].TryFormat(stringBuffer.Slice(2 * i), out _, "x2");
            }
            return new string(stringBuffer);
        }
    }
    

    You can optimize it even more if you are sure that your strings are small enough and replace encoding.GetBytes by unsafe int GetBytes(ReadOnlySpan chars, Span bytes) alternative.

提交回复
热议问题