Is the hash different in SQL and C #?

In my database, I have SQL,

DECLARE @InputString nvarchar(15) ='pass' DECLARE @InputSalt nvarchar(36) = 'FC94C37C-03A3-49A3-9B9F-D4A82E708618' DECLARE @HashThis nvarchar(100) Declare @BinaryHash varbinary(max) set @HashThis = @InputString + @InputSalt set @BinaryHash= HASHBYTES('SHA1', @HashThis) SELECT CAST(N'' AS XML).value('xs:base64Binary(xs:hexBinary(sql:variable("@BinaryHash")))', 'VARCHAR(MAX)') 

and C # I,

 public static string HashString(string cleartext) { byte[] clearBytes = System.Text.Encoding.UTF8.GetBytes(cleartext); return HashBytes(clearBytes); } public static string HashBytes(byte[] clearBytes) { var hasher = System.Security.Cryptography.SHA1.Create(); byte[] hashBytes = hasher.ComputeHash(clearBytes); string hash = System.Convert.ToBase64String(hashBytes); hasher.Clear(); return hash; } HashString("passFC94C37C-03A3-49A3-9B9F-D4A82E708618") 

But the hash is different?

 C# Output: S55Nz1lyGweoJEHWcC6zFxJDKWQ= SQL Output: 4jqyC1pLJ0hW+AMNk8GOWCC99KY= 

https://dotnetfiddle.net/4bwAtm

+7
c # sql sql-server-2012
source share
1 answer

Your hash function is performed by bytes, not by characters. You efficiently translate characters into bytes, but in C # you do not do the same as in SQL: you use nvarchar (UTF-16) from SQL, you use UTF-8 from C #. You can change either according to another.

Since you do not have non-ASCII characters in the current test, for this particular password you can easily verify that this is a problem by simply changing nvarchar to varchar in your SQL. This will not be enough for the entire range of Unicode characters.

+6
source share

All Articles