1

I want to compare password when user logins from ASP.NET Site to One I generated for him in SQL Server.

So, I generate password field in SQL server like this:

insert into users 
select 'username',  HASHBYTES('SHA2_512', CONVERT(nvarchar(4000),'password'))

And code in C#:

string text = Password;
            SHA512 alg = SHA512.Create();
            byte[] result = alg.ComputeHash(Encoding.UTF8.GetBytes(text));
            string hash = Encoding.UTF8.GetString(result);

And those two hashes are very different.

Where am I wrong?

el ninho
  • 4,183
  • 15
  • 56
  • 77

1 Answers1

1

NVARCHAR is a 16-bit encoding — most likely little-endian UTF-16. HASHBYTES is therefore probably seeing a different input to ComputeHash.

Try Encoding.Unicode.

Also, don't use Encoding to convert result to a string. It contains raw bytes, not encodings of characters. If you want a string, convert the bytes to hex digits or Base64.

Community
  • 1
  • 1
Marcelo Cantos
  • 181,030
  • 38
  • 327
  • 365