0

Goal:
Retrieve the same hash value from SQL and C# code.

Problem:
The value of the hash is almost the same. I'm using the same hash and sha.

Input:
"Hello World!'"

C# code:
https://dotnetfiddle.net/2YbFXY

SQL code:

DECLARE @HashThis varchar(32);  
SET @HashThis = CONVERT(varchar(32),'Hello World!');  
SELECT HASHBYTES('SHA2_256', @HashThis);

Output:
Result of C# code:

"7f83b1657ff1fc53b92dc18148a1d65dfc2d4b1fa3d677284addd200126d9069"

Result of SQL code:

"0x7F83B1657FF1FC53B92DC18148A1D65DFC2D4B1FA3D677284ADDD200126D9069"

Is there a good or recommended approach to remove the data "0x"?

Thank you!

HelloWorld1
  • 13,688
  • 28
  • 82
  • 145
  • Does [this](https://stackoverflow.com/questions/8186965/what-do-numbers-using-0x-notation-mean#:~:text=In%20C%20and%20languages%20based,1024%2C%20or%20one%20binary%20K.) help? Otherwise you could just detect the `0x` in the hash with `StartsWith` and remove the first two characters. – funie200 Jul 15 '20 at 12:07
  • 6
    you can say the hash code IS the same, only the representation differs. Removing the 0x and downcasing makes it suitable for comparison. – ruud Jul 15 '20 at 12:08
  • 1
    The hashes are identical, formatted differently. A *hash* isn't a string anyway, it's a binary value. If you want to store and compare the actual hash values, don't format them as strings – Panagiotis Kanavos Jul 15 '20 at 12:17
  • Do you have to convert the hashes to strings? The real hash values are the byte[] `data` variable in your C# code and the binary value returned by `HASHBYTES` – Panagiotis Kanavos Jul 15 '20 at 12:21

2 Answers2

2

Change SELECT HASHBYTES('SHA2_256', @HashThis); to

SELECT SUBSTRING(master.dbo.fn_varbintohexstr(HashBytes('SHA2_256', @HashThis)), 3, 64)

Taken from Convert HashBytes to VarChar

As @Magnus pointed out in the comments, substring length should be 64.

Arska
  • 33
  • 8
0

This should do it:

DECLARE @HashThis varchar(32);  
SET @HashThis = CONVERT(varchar(32),'Hello World!');  
SELECT CONVERT(char(64), HASHBYTES('SHA2_256', @HashThis), 2)

But if you send down a binary to the database you should be able to compare that to the result of HASHBYTES without any convert. The same if you bring it up to you C# app as byte[].

Magnus
  • 45,362
  • 8
  • 80
  • 118