Calculate a MD5 hash from a string

后端 未结 16 2024
独厮守ぢ
独厮守ぢ 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:56
    StringBuilder sb= new StringBuilder();
    for (int i = 0; i < tmpHash.Length; i++)
    {
       sb.Append(tmpHash[i].ToString("x2"));
    }
    
    0 讨论(0)
  • 2020-11-28 21:57

    Was trying to create a string representation of MD5 hash using LINQ, however, none of the answers were LINQ solutions, therefore adding this to the smorgasbord of available solutions.

    string result;
    using (MD5 hash = MD5.Create())
    {
        result = String.Join
        (
            "",
            from ba in hash.ComputeHash
            (
                Encoding.UTF8.GetBytes(observedText)
            ) 
            select ba.ToString("x2")
        );
    }
    
    0 讨论(0)
  • 2020-11-28 21:57

    Support string and file stream.

    examples

    string hashString = EasyMD5.Hash("My String");
    
    string hashFile = EasyMD5.Hash(System.IO.File.OpenRead("myFile.txt"));
    

    -

       class EasyMD5
            {
                private static string GetMd5Hash(byte[] data)
                {
                    StringBuilder sBuilder = new StringBuilder();
                    for (int i = 0; i < data.Length; i++)
                        sBuilder.Append(data[i].ToString("x2"));
                    return sBuilder.ToString();
                }
    
                private static bool VerifyMd5Hash(byte[] data, string hash)
                {
                    return 0 == StringComparer.OrdinalIgnoreCase.Compare(GetMd5Hash(data), hash);
                }
    
                public static string Hash(string data)
                {
                    using (var md5 = MD5.Create())
                        return GetMd5Hash(md5.ComputeHash(Encoding.UTF8.GetBytes(data)));
                }
                public static string Hash(FileStream data)
                {
                    using (var md5 = MD5.Create())
                        return GetMd5Hash(md5.ComputeHash(data));
                }
    
                public static bool Verify(string data, string hash)
                {
                    using (var md5 = MD5.Create())
                        return VerifyMd5Hash(md5.ComputeHash(Encoding.UTF8.GetBytes(data)), hash);
                }
    
                public static bool Verify(FileStream data, string hash)
                {
                    using (var md5 = MD5.Create())
                        return VerifyMd5Hash(md5.ComputeHash(data), hash);
                }
            }
    
    0 讨论(0)
  • This solution requires c# 8 and takes advantage of Span<T>. Note, you would still need to call .Replace("-", string.Empty).ToLowerInvariant() to format the result if necessary.

    public static string CreateMD5(ReadOnlySpan<char> input)
    {
        var encoding = System.Text.Encoding.UTF8;
        var inputByteCount = encoding.GetByteCount(input);
        using var md5 = System.Security.Cryptography.MD5.Create();
    
        Span<byte> bytes = inputByteCount < 1024
            ? stackalloc byte[inputByteCount]
            : new byte[inputByteCount];
        Span<byte> destination = stackalloc byte[md5.HashSize / 8];
    
        encoding.GetBytes(input, bytes);
    
        // checking the result is not required because this only returns false if "(destination.Length < HashSizeValue/8)", which is never true in this case
        md5.TryComputeHash(bytes, destination, out int _bytesWritten);
    
        return BitConverter.ToString(destination.ToArray());
    }
    
    0 讨论(0)
  • 2020-11-28 22:00

    A MD5 hash is 128 bits, so you can't represent it in hex with less than 32 characters...

    0 讨论(0)
  • 2020-11-28 22:02

    I suppose it is better to use UTF-8 encoding in the string MD5.

    public static string MD5(this string s)
    {
        using (var provider = System.Security.Cryptography.MD5.Create())
        {
            StringBuilder builder = new StringBuilder();                           
    
            foreach (byte b in provider.ComputeHash(Encoding.UTF8.GetBytes(s)))
                builder.Append(b.ToString("x2").ToLower());
    
            return builder.ToString();
        }
    }
    
    0 讨论(0)
提交回复
热议问题