-1

I'm trying to move authentication from the stored procedure to EF. The SQL itself is returning 2 results. How should I validate them?

The value is to be checked against the value stored in the table

ECC2065575DCBF977CD923996C598C3DC481404E

SQL syntax:

Declare @Password AS NVARCHAR(256) = 'Quest_2016'

DECLARE @PasswordSalt AS NVARCHAR(5) = 'LCY''n'

DECLARE @PasswordWithSalt AS NVARCHAR(261) = @Password + @PasswordSalt

print @PasswordWithSalt

result:1 Quest_2016LCY'n

print HASHBYTES(N'SHA1', @PasswordWithSalt )

result 2: 0xECC2065575DCBF977CD923996C598C3DC481404E-----

print HASHBYTES(N'SHA1', 'Quest_2016LCY''n')

result 3: 0x5E85AB2ED11CDB696BC0544131D7C8571F4F8FA8-----

Also just what how this can be implemented in C#

sql hashbytes

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Prateek Chauhan
  • 47
  • 1
  • 1
  • 5

1 Answers1

4

The problem with those two queries is that the string values are the same but the bytes are not.

The first query

print HASHBYTES(N'SHA1', @PasswordWithSalt )

uses unicode encoding to get the bytes so every character is 2 bytes (0x510075006500730074005F0032003000310036004C004300590027006E00).

The second query

print HASHBYTES(N'SHA1', 'Quest_2016LCY''n')

uses ASCII so that every character is one byte.

To have the same result in the second example prefix the String with N'. It will tell SQL server that this is a unicode string

print HASHBYTES(N'SHA1', N'Quest_2016LCY''n')

produces the hash 0xECC2065575DCBF977CD923996C598C3DC481404E

In C# you can also use SHA1 to get the hash of the string and here also you need to be specific about the byte encoding

byte[] data = Encoding.Unicode.GetBytes(@"Quest_2016LCY'n");
byte[] hash = SHA1.Create().ComputeHash(data);
Console.Write(hash.Select(x=>x.ToString("X2")).Aggregate((x,y)=>x+y));

prints ECC2065575DCBF977CD923996C598C3DC481404E but if you change Encoding.Unicode to Encoding.ASCII it gives the 5E85AB2ED11CDB696BC0544131D7C8571F4F8FA8.

Paweł Łukasik
  • 3,893
  • 1
  • 24
  • 36