Calculate a MD5 hash from a string

后端 未结 16 2023
独厮守ぢ
独厮守ぢ 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 22:04

    Here is my utility function for UTF8, which can be replaced with ASCII if desired:

        public static byte[] MD5Hash(string message)
        {
            return MD5.Create().ComputeHash(Encoding.UTF8.GetBytes(message));
        }
    
    0 讨论(0)
  • 2020-11-28 22:08

    Idk anything about 16 character hex strings....

    using System;
    using System.Security.Cryptography;
    using System.Text;
    

    But here is mine for creating MD5 hash in one line.

    string hash = BitConverter.ToString(MD5.Create().ComputeHash(Encoding.ASCII.GetBytes("THIS STRING TO MD5"))).Replace("-","");
    
    0 讨论(0)
  • 2020-11-28 22:11
    // given, a password in a string
    string password = @"1234abcd";
    
    // byte array representation of that string
    byte[] encodedPassword = new UTF8Encoding().GetBytes(password);
    
    // need MD5 to calculate the hash
    byte[] hash = ((HashAlgorithm) CryptoConfig.CreateFromName("MD5")).ComputeHash(encodedPassword);
    
    // string representation (similar to UNIX format)
    string encoded = BitConverter.ToString(hash)
       // without dashes
       .Replace("-", string.Empty)
       // make lowercase
       .ToLower();
    
    // encoded contains the hash you want
    
    0 讨论(0)
  • 2020-11-28 22:12

    I'd like to offer an alternative that appears to perform at least 10% faster than craigdfrench's answer in my tests (.NET 4.7.2):

    public static string GetMD5Hash(string text)
    {
        using ( var md5 = MD5.Create() )
        {
            byte[] computedHash = md5.ComputeHash( Encoding.UTF8.GetBytes(text) );
            return new System.Runtime.Remoting.Metadata.W3cXsd2001.SoapHexBinary(computedHash).ToString();
        }
    }
    

    If you prefer to have using System.Runtime.Remoting.Metadata.W3cXsd2001; at the top, the method body can be made an easier to read one-liner:

    using ( var md5 = MD5.Create() )
    {
        return new SoapHexBinary( md5.ComputeHash( Encoding.UTF8.GetBytes(text) ) ).ToString();
    }
    

    Obvious enough, but for completeness, in OP's context it would be used as:

    sSourceData = "MySourceData";
    tmpHash = GetMD5Hash(sSourceData);
    
    0 讨论(0)
提交回复
热议问题