0

My C# code produces the same hash as the online hash calculator and as my old Basic library, and others:

var sha256 = SHA256.Create();
var hashed = sha256.ComputeHash(Encoding.UTF8.GetBytes(_checksum));
_checksum = BitConverter.ToString(hashed).Replace("-", "").ToLower();

For example,

"test" -> "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08"

I have to reproduce the same hash directly from a SQL Server command, if I use

SELECT master.dbo.fn_varbintohexsubstring(0, HashBytes('SHA2_256', 'test'), 1, 0)
=> "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08"

BUT if I try to use one of my columns, it produce a different result:

SELECT master.dbo.fn_varbintohexsubstring(0, HashBytes('SHA2_256', t.sMANAGER), 1, 0)
FROM EV_AGENCY t
=> "fe520676b1a1d93dabab2319eea03674f3632eaeeb163d1e88244f5eb1de10eb"

The column is a nvarchar, collation is French_CI_AI.

I assumed that I have to cast correctly my column, so I try cast, convert, etc without success.

Can someone help me with that ?

Thank you !

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
iguypouf
  • 770
  • 4
  • 15
  • 2
    You have a problem with the `nvarchar`: it is UTF-16. But C#-side you are using UTF8... The easiest thing is to use UTF-16 C#-side, the more complex thing is to convert to UTF8 T-SQL-side. – xanatos Mar 29 '17 at 10:29
  • If you think the other question isn't similar enough to yours then reply to me and I'll reopen this question. – xanatos Mar 29 '17 at 10:41
  • xanatos, the UDF did the trick. Amazing, thank you for your *Clairvoyance* – iguypouf Mar 29 '17 at 11:25

0 Answers0