2

I have intercepted the word "admin" using this c# code

Byte[] inputBytes = Encoding.UTF8.GetBytes(stringpassword);
SHA512 shaM = new SHA512Managed();
Byte[] hashedBytes = shaM.ComputeHash(inputBytes);

string hashedpassword = BitConverter.ToString(hashedBytes);

and got the result of this "DA-EF-49-53-B9-78-33-65-CA-D6-61-52-23-72-05-06-CC". and I encrypyt the same word "admin" using SQL stored procedure

SET @password = HASHBYTES('SHA2_512',@password);

and get this as output "Ç­DË­v*] ¤RùèTýÁàç¥*8_#óê±Ø“ÔrcMúÇÓN¼5Ñj·ûŠÈ"

Why is there difference between these to methods?

Philippe
  • 1,733
  • 1
  • 14
  • 28

1 Answers1

7

From the documentation of the HASHBYTES function:

Return Value

varbinary (maximum 8000 bytes)

The issue here is that you're trying to interpret arbitrary binary data (the output of HASHBYTES) as a textual value, which just won't work. In this case SQL server is trying to interpret the raw byte values as characters in whatever collation your database is using.

The standard way of representing binary data in a textual form is to convert it to a base64 representation. To do this in C# replace the last line with:

string hashedpassword = Convert.ToBase64String(hashedBytes);

Then in your SQL you can do the following to convert your hashed value to base64 (based on this SO answer):

DECLARE @hashedValue VARBINARY(8000) = HASHBYTES('SHA2_512', 'admin')
SELECT
    CAST(N'' AS XML).value(
          'xs:base64Binary(xs:hexBinary(sql:column("bin")))'
        , 'VARCHAR(MAX)'
    )   Base64Encoding
FROM (
    SELECT @hashedValue AS bin
) AS bin_sql_server_temp;

If you run this you will observe that the base64 encoded values are identical.

Community
  • 1
  • 1
Jared Russell
  • 10,804
  • 6
  • 30
  • 31