tags:

views:

438

answers:

4

Good evening all,

I've been working on an MD5 tool in C# that takes a file, goes through my Hasher class and pops the result in a database, along with the filename and directory.

The issue I'm having is that each time I run the test, the MD5 result for the same identical file i.e. unchanged in any way is completely different.

Below is the code I use

        string md5Result = "";
        HashAlgorithm hmacMd5 = new HMACMD5(); 
        byte[] hash;
        try
        {
            using (Stream fileStream = new FileStream(fileLocation, FileMode.Open))
            {
                using (Stream bufferedStream = new BufferedStream(fileStream, 5600000))
                {
                    hash = hmacMd5.ComputeHash(bufferedStream);
                    foreach (byte x in hash)
                    {
                        md5Result += x;
                    }
                }
            }
        }
        catch (UnauthorizedAccessException uae) { }



        return md5Result;

Here are the results for 3 seperate runs of hello.mp2:

1401401571161052548110297623915056204169177

16724366215610475211823021169211793421

56154777074212779619017828183239971

Quite puzzling. My only rational thought as to why I'm getting these results is with concatenating byte to string.

Can anyone spot an issue here?

Regards,

Ric

A: 

You shouldn't have a bufferedStream in between. I would guess a different number of bytes is buffered in each run.

Zed
+8  A: 

You should use System.Security.Cryptography.MD5 rather.

HMACMD5 doesn't compute a hash, it computes a message authentication code.

HMACMD5 is a type of keyed hash algorithm that is constructed from the MD5 hash function and used as a Hash-based Message Authentication Code (HMAC). The HMAC process mixes a secret key with the message data, hashes the result with the hash function, mixes that hash value with the secret key again, then applies the hash function a second time. The output hash will be 128 bits in length

Since you're not supplying the HMAC key, one is being generated randomly for you on your behalf and causing you to see different results.

nos
+1  A: 

My suggestion is that you are not computing MD5 hashes since MD5 produces a fixed length output of 32 hex numbers

Also, since you don't see any numbers from 0xA to 0xF is quite puzzling

You might wanna check a "real" result with online MD5 calculators such as this one

Eric
A: 

You might want to use this API: http://www.filemd5.net/API instead of writing the MD5 algo yourself

JohnnieWalker