8

I'm working on a C# project where we have a text value that is placed in a SQL Server database table in a nvarchar field. The value is hashed using the code below:

byte[] data = Encoding.ASCII.GetBytes("valuetohash");
byte[] bytes = new SHA512Managed().ComputeHash(data);
String result = Encoding.ASCII.GetString(bytes);

Now I need to duplicate creating that same value using T-SQL.

Can someone tell me how I can do that?

I tried HASHBYTES ( 'SHA2_512', 'valuetohash' )

but that lacks the ASCII encoding and produces a different value.

2
  • Just fixed a typo in the title, sorry about that. Commented Sep 13, 2016 at 11:06
  • Create a CLR Scalar-Valued function, see here Commented Sep 13, 2016 at 11:08

1 Answer 1

19

You need to convert binary data to a Base64 string and you may try using the CONVERT function:

SELECT CONVERT(varchar(max), HASHBYTES ('SHA2_512', 'valuetohash') ,2) 
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks Trifon, your answer is quite excellent, however did not solve my problem. The values the software places in the db look like "?m???d????" strings, they are not in base64 format. I'm not sure why. Thanks for this comment anyway.
In my environment the above command returns this string: C7458FE820F7567EE61763D6789C1D86E57754F0A51C8CDF4BE08CB17DEB871F396EBFD88F595A8AE7313CEE19FBC67C37AD5DD4500B3DD8523F886BF1DDCCBA
It is important to note here, that the resulting hash changes depending on whether your input string has the type varchar or nvarchar.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.