Thursday, June 14, 2012

SQLServer HASHBYTES and .Net result mismatch

This nearly made me nuts.

I have at SqlServer side 3 fields:
nvarchar(3000) Message,
nvarchar(500) FilePath,
nchar(10) Line

Calculated hash on those 3 fields like:
HASHVALUE('SHA1', Message + FilePath + Line).

on .Net side I did:
private byte[] GetHash(string value)
 {
            System.Security.Cryptography.SHA1Managed x = 
                       new System.Security.Cryptography.SHA1Managed();
            byte[] bs = System.Text.Encoding.UTF8.GetBytes(value);
            return  x.ComputeHash(bs);
 }

and calculated hash on Message + FilePath + Line; where those are strings taken from an xml file....

MISMATCH.

Ok, thought I, that is probably encoding... Tried all possible - nope, still mismatch.

To make long story short:
it is difference in how nvarchar and varchar are saved at SqlServer. After I fixed my hash at SqlServer to be:
HASHBYTES('SHA1', Convert(varchar(max),message + filepath) + LTRIM(RTRIM(Convert(varchar(10),line))))

It all worked as charm producing correct and equal to .Net hash.

1 comment: