Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't my .net-calculated MD5 hash equivalent to the hash calculated on a web site?

I am trying to generate equivalent MD5 hashes in both JavaScript and .Net. Not having done either, I decided to use against a third party calculation - this web site for the word "password". I will add in salts later, but at the moment, I can't get the .net version to match up with the web site's hash:

5f4dcc3b5aa765d61d8327deb882cf99

I'm guessing it is an encoding problem, but I've tried about 8 different variations of methods for calculating an MD5 hash in .Net, and none of them match what I have obtained in JavaScript (or from the web site). This MSDN example is one of the methods I have tried, which results in this hash which i have commonly received:

7c6a180b36896a0a8c02787eeafb0e4c

Edit: Sadly, I've accidentally been providing different source strings to the two different implementations. EBSAK. :-/ Still be interested to hear your answer to the follow-up.

Bonus question: what encoding/format would be best to store hashed values in a database?

like image 647
pc1oad1etter Avatar asked Oct 10 '08 05:10

pc1oad1etter


2 Answers

Running the code from the MSDN site you quote:

 // Hash an input string and return the hash as
    // a 32 character hexadecimal string.
    static string getMd5Hash(string input)
    {
            // Create a new instance of the MD5CryptoServiceProvider object.
            MD5 md5Hasher = MD5.Create();

            // Convert the input string to a byte array and compute the hash.
            byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(input));

            // Create a new Stringbuilder to collect the bytes
            // and create a string.
            StringBuilder sBuilder = new StringBuilder();

            // Loop through each byte of the hashed data 
            // and format each one as a hexadecimal string.
            for (int i = 0; i < data.Length; i++)
            {
                sBuilder.Append(data[i].ToString("x2"));
            }

            // Return the hexadecimal string.
            return sBuilder.ToString();
        }


        static void Main(string[] args)
        {
            System.Console.WriteLine(getMd5Hash("password"));
        }

returns:

5f4dcc3b5aa765d61d8327deb882cf99
like image 105
shoosh Avatar answered Nov 15 '22 03:11

shoosh


This is happening because somehow you are hashing password1 instead of password, or perhaps calculating the password incorrectly and it somehow mysteriously equals password1.

You can do a reverse lookup of the md5 hash you provided by googling

7c6a180b36896a0a8c02787eeafb0e4c
like image 26
sharkswithlasers Avatar answered Nov 15 '22 03:11

sharkswithlasers