Calculate a MD5 hash from a string

290,448

Solution 1

As per MSDN

Create MD5:

public static string CreateMD5(string input)
{
    // Use input string to calculate MD5 hash
    using (System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create())
    {
        byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input);
        byte[] hashBytes = md5.ComputeHash(inputBytes);

        return Convert.ToHexString(hashBytes); // .NET 5 +

        // Convert the byte array to hexadecimal string prior to .NET 5
        // StringBuilder sb = new System.Text.StringBuilder();
        // for (int i = 0; i < hashBytes.Length; i++)
        // {
        //     sb.Append(hashBytes[i].ToString("X2"));
        // }
        // return sb.ToString();
    }
}

Solution 2

// 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

Solution 3

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")
    );
}

Solution 4

You can use Convert.ToBase64String to convert 16 byte output of MD5 to a ~24 char string. A little bit better without reducing security. (j9JIbSY8HuT89/pwdC8jlw== for your example)

Solution 5

Depends entirely on what you are trying to achieve. Technically, you could just take the first 12 characters from the result of the MD5 hash, but the specification of MD5 is to generate a 32 char one.

Reducing the size of the hash reduces the security, and increases the chance of collisions and the system being broken.

Perhaps if you let us know more about what you are trying to achieve we may be able to assist more.

Share:
290,448

Related videos on Youtube

Muhamad Jafarnejad
Author by

Muhamad Jafarnejad

Web and Android Developer.

Updated on July 08, 2022

Comments

  • Muhamad Jafarnejad
    Muhamad Jafarnejad almost 2 years

    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

    string sSourceData;
    byte[] tmpSource;
    byte[] tmpHash;
    sSourceData = "MySourceData";
    
    //Create a byte array from source data.
    tmpSource = ASCIIEncoding.ASCII.GetBytes(sSourceData);
    tmpHash = new MD5CryptoServiceProvider().ComputeHash(tmpSource);
    
    // and then convert tmpHash to string...
    

    Is there a way to use code like this to generate a 16-character hex string (or 12-character string)? A 32-character hex string is good but I think it'll be boring for the customer to enter the code!

    • Danger Saints
      Danger Saints almost 3 years
      MD5CryptoServiceProvider instance should be disposed
  • KingCronus
    KingCronus almost 12 years
    A nice workaround, but I doubt he OP will want to have it case-sensitive and with special chars...
  • Muhamad Jafarnejad
    Muhamad Jafarnejad almost 12 years
    thanks for your answer. and sorry about my bad explanation. I want to publish an application for windows, the user should buy the license to use my application, so my application request two fields: USERNAME: ... , and KEY: .... I want to hash the USERNAME and create the KEY, then the user should enter the specific USERNAME and KEY. my problem here is that the KEY should be 12-characters, (But in MD5 hash, I get the 32-char KEY). please help me, i really need it.
  • yǝsʞǝla
    yǝsʞǝla about 9 years
  • Igor Gatis
    Igor Gatis about 9 years
    Why "similar to UNIX format"? What it is not exactly the same?
  • DavidG
    DavidG over 8 years
    You should always say where you get code from if you copy/paste from somewhere, otherwise it is classed as plagiarism.
  • Paolo Iommarini
    Paolo Iommarini over 8 years
    The class MD5 implements IDisposable, remember to dispose your instance. ;)
  • Oliver Bock
    Oliver Bock about 8 years
    In general you should hash a lossless text encoding, like UTF8.
  • Monsignor
    Monsignor almost 7 years
    BTW checked with the BenchmarkDotNet that the combination of Cryptography.MD5 and BitConverter (see @Michaels's answer) has the best performance.
  • bh_earth0
    bh_earth0 about 6 years
    this gives different result from online md5 checkers. or is it just me??
  • bh_earth0
    bh_earth0 about 6 years
    if you use UTF8, it puts bytordermark(bom). file_content and string WON'T match. to get rid of bom, i used new utf8encoding(false); when file.read/write
  • Richard Schneider
    Richard Schneider over 5 years
    Its better to System.Text.Encoding.Utf8.GetBytesfor people outside of USA.
  • Prashant Pimpale
    Prashant Pimpale over 5 years
    @Anant How to decrypt the MD5?
  • Anant Dabhi
    Anant Dabhi over 5 years
    @PrashantPimpale MD5 is a digest algorithm. Think of it as converting a cow into a steak.
  • Prashant Pimpale
    Prashant Pimpale over 5 years
    Yes tried with TripleDESCryptoServiceProvider and done!
  • Prashant Pimpale
    Prashant Pimpale over 5 years
    just wanted to encrypt an Email Id and then decrypt it
  • eddyP23
    eddyP23 about 5 years
    @bh_earth0 it seems that BitConverter doesn't work in the same fashion on windows and linux, see this question: stackoverflow.com/questions/11454004/…
  • Klesun
    Klesun almost 5 years
    What does the "X2" mean?
  • Anant Dabhi
    Anant Dabhi almost 5 years
    @ArturKlesun , It formats the string as two uppercase hexadecimal characters.
  • Marc.2377
    Marc.2377 over 4 years
    One-liner, in method syntax: return string.Join( "", hash.ComputeHash( Encoding.UTF8.GetBytes(observedText) ).Select( x => x.ToString("x2") ) );
  • Marc.2377
    Marc.2377 over 4 years
    ... in which case, I propose return string.Concat( hash.ComputeHash( Encoding.UTF8.GetBytes(observedText) ).Select( x => x.ToString("x2") ) ); instead. It's a little bit shorter, possibly clearer intention, and performs marginally faster (<10% perf. increase).
  • jklemmack
    jklemmack almost 4 years
    @PrashantPimpale MD5 is one way - it can create a hash, but information is destroyed and cannot be recovered. It's value comes from hashing two different things then comparing the hashes. Works well for things like passwords, or comparing file contents. If you want to reverse "encryption", the look at things like AES or DES (docs.microsoft.com/en-us/dotnet/api/…). They provide the ability to "encrypt" then "decrypt"
  • Detail
    Detail over 3 years
    This worked nicely for me when trying to convert an MD5 Hash (from Azure Blob properties) into a string. It produces exactly the same string as the Azure Storage container does.
  • Jawad Zeb
    Jawad Zeb over 3 years
    for those who are trying to calculate for Sip or an equivalent to linux md5sum don't forget to add .ToLower()
  • Kurtis Jungersen
    Kurtis Jungersen almost 3 years
    NOTE: "Due to collision problems with MD5/SHA1, Microsoft recommends SHA256 or SHA512. Consider using the SHA256 class or the SHA512 class instead of the MD5 class. Use MD5 only for compatibility with legacy applications and data." Sources: 1) MD5 Docs linked by OP, where this notice appears, and 2) MS Docs on SHA256, with a good example
  • Rey
    Rey over 2 years
    This does not dispose the instance of MD5
  • nivs1978
    nivs1978 over 2 years
    Remember a "using": using (var md5 = MD5.Create()) md5.ComputeHash(....);
  • Ivandro Jao
    Ivandro Jao over 2 years
    Using BitConverter.ToString() also gives a nice hash-string!