2

I'm using to hash a password using MD5 programatically, but when i compared MD5 hashes created in C# and MD5 hashes created by an SQL Server ( HASHBYTES('MD5', 'admin') ) the result is not same.

How come they are not the same? How to solve this problem?

Also how should I store MD5 in sql server 2008 R2. Using varbinary(max) or binary(16)?

Cheesebaron
  • 24,131
  • 15
  • 66
  • 118
Willy
  • 1,689
  • 7
  • 36
  • 79
  • See also https://stackoverflow.com/questions/35200452/compute-md5-hash-of-a-utf8-string/35289890#35289890 for computing a hash of UTF-8 characters – Ben Oct 11 '17 at 20:37

1 Answers1

2

In addition to Reza M.A answer, you should get good results using HASHBYTES(). However, order of bytes may be the issue. In SQL server 2005+ it's easy to reverse order bytes by making a few conversions and suing built-in REVERSE().

DECLARE 
    @test varchar(MAX),
    @vbTest varbinary(MAX)

SET @test = 'admin'
SET @vbTest = CONVERT(varbinary(max), @test, 0)

SELECT 
    HASHBYTES('MD5', @vbTest),
    CAST(
        REVERSE(
            CAST(
                HASHBYTES('MD5', @vbTest) 
            AS varchar(max))
        ) 
    AS varbinary(max))

I believe you should store hash output as varbinary(max), if it is output from HASHBYTES(). Otherwise, store it as your orginal value type - if it is binary(16), then use that.

OzrenTkalcecKrznaric
  • 5,535
  • 4
  • 34
  • 57