Knows Not Much
Knows Not Much

Reputation: 31546

Write T-SQL functionality in .NET

I have this bit of t-sql code

set @UrlHash = convert(bigint, hashbytes('MD5', @Url))  

I wonder if I can write a function in C# which returns me the exact same hash as the line above without going to SQL.

Is it possible?

Requirement is that C# MUST created exact same hash.

Upvotes: 1

Views: 413

Answers (3)

sloth
sloth

Reputation: 101052

The select

SELECT CONVERT(BIGINT, HASHBYTES('MD5', 'http://stackoverflow.com')) 

will yield the following result:

-3354682182756996262

If you now try to create a MD5 hash in C#

MD5 md5 = MD5.Create();
byte[] textToHash = Encoding.UTF8.GetBytes("http://stackoverflow.com");
byte[] result = md5.ComputeHash(textToHash); 
long numeric = BitConverter.ToInt64(result, 0);

numeric will be 8957512937738269783.


So what's the issue (besides the fact that a MD5 hash is 128-bit and BIGINT/long is just 64-bit)?

It's an endian issue (the bytes are in the wrong order). Let's fix it using the BitConverter class and reverse the bytes as needed:

MD5 md5 = MD5.Create();
byte[] textToHash = Encoding.UTF8.GetBytes("http://stackoverflow.com");
byte[] result = md5.ComputeHash(textToHash); 

if (BitConverter.IsLittleEndian)
    Array.Reverse(result);

long numeric = BitConverter.ToInt64(result, 0);

numeric is now -3354682182756996262 as you want.

Upvotes: 7

Antonio Bakula
Antonio Bakula

Reputation: 20693

You should use MD5 class, here is the example from http://blogs.msdn.com/b/csharpfaq/archive/2006/10/09/how-do-i-calculate-a-md5-hash-from-a-string_3f00_.aspx, with output as int 64 :

public int64 CalculateMD5Hash(string input)
{
    // step 1, calculate MD5 hash from input
    MD5 md5 = System.Security.Cryptography.MD5.Create();
    byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input);
    byte[] hash = md5.ComputeHash(inputBytes);

    return BitConverter.ToInt64(hash, 0);
}

Upvotes: 0

reverse_engineer
reverse_engineer

Reputation: 4269

Isn't an MD5 hash standard? Can't you use a standard MD5 C# implementation? What about using the code in here?

Upvotes: -1

Related Questions