12

I have a method used to generate a hash:

public static string GetMD5Hash(string input)
    {
        System.Security.Cryptography.MD5CryptoServiceProvider x = new System.Security.Cryptography.MD5CryptoServiceProvider();
        byte[] bs = System.Text.Encoding.UTF8.GetBytes(input);

        bs = x.ComputeHash(bs);

        System.Text.StringBuilder s = new System.Text.StringBuilder();

        foreach (byte b in bs)
        {
            s.Append(b.ToString("x2").ToLower());
        }
        return s.ToString();
    }

I then save that hash in a varchar(255) column. Knowing what the original input string was, would it be possible to to arrive at the same hash value stored in the varchar(255) column, using sql (2005)??

I have tried like crazy using different data types, conversions and the hashbytes() function, but have not been able to get close.

Example of my failed attempt :(

select convert(varchar, hashbytes('MD5', convert(varbinary(200), '<censored>',0)))
4
  • Don't use MD5; it's insecure.
    – SLaks
    Jun 28, 2011 at 13:09
  • 1
    why varchar(255) ? MD5CryptoServiceProvider returns a 16 byte array from ComputeHash() so you should use char(32) (if you save it as hex that is) Jun 28, 2011 at 13:11
  • maybe it's because of ToLower()?
    – Greenisha
    Jun 28, 2011 at 13:14
  • 1
    @Slaks - It may be that this is not a security issue and perhaps the OP is using the hash as a kind of checksum or to quickly locate records in the DB.
    – El Ronnoco
    Oct 1, 2012 at 15:45

2 Answers 2

5

from #c with "bleepbloop" : 04d3f95947702213e23730a0e8fac6c3

Then

select convert(varchar(32), hashbytes('MD5', 'bleepbloop'), 2)

>> 04D3F95947702213E23730A0E8FAC6C3

Or You could just store & compare as binary.

0
3

The problem here is that x2 is getting the hex encoding of the data, where-as convert is getting your server's configured decoding of the bytes (which isn't really valid, since that data is not text-based). Very different things. If you keep as varbinary and compare to a byte[] you should be fine.

If you are using SQL Server 2008, you can also use:

select convert(varchar(32), hashbytes('MD5', convert(varbinary(200),
           '<censored>',0)), 2)

to get the hex-encoded version (you can use 1 instead of 2 to get a leading 0x)

1
  • Thanks for the response and extra info.
    – Craigt
    Jun 28, 2011 at 13:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.