2

when I get a hash from C# I seem to get a different value then when I do it in sql server.

Take this query

declare @test table (value nvarchar(100))
insert into @test values ('1234'), (N'1234')

select 'from db' as source, t.value, HASHBYTES('SHA2_256', t.value) as result from @test t
union all
select 'fixed ascii', '1234', HASHBYTES('SHA2_256', '1234')
union all
select 'fixed unicode', N'1234', HASHBYTES('SHA2_256', N'1234')

the result is

source value result
from db 1234 0x4F37C061F1854F9682F543FECB5EE9D652C803235970202DE97C6E40C8361766
from db 1234 0x4F37C061F1854F9682F543FECB5EE9D652C803235970202DE97C6E40C8361766
fixed ascii 1234 0x03AC674216F3E15C761EE1A5E255F067953623C8B388B4459E13F978D7C846F4
fixed unicode 1234 0x4F37C061F1854F9682F543FECB5EE9D652C803235970202DE97C6E40C8361766

As you can see in the result, only the fixed ascii version has a different result, as I would also expect since the column has datatype nvarchar

Now I want to get the hash in C#

private string GetStringSha256Hash(string text, System.Text.Encoding coding)
{
    string result = "";

    if (String.IsNullOrEmpty(text) == false)
    {
        using (var sha = new System.Security.Cryptography.SHA256Managed())
        {
            byte[] textData = coding.GetBytes(text);
            byte[] hash = sha.ComputeHash(textData);
            result = BitConverter.ToString(hash).Replace("-", String.Empty);
        }
    }

    return result;
}

string dbPass = TextEditPass.Text;
string hashedPassUTF8 = GetStringSha256Hash(dbPass, System.Text.Encoding.UTF8);
string hashedPassASCII = GetStringSha256Hash(dbPass, System.Text.Encoding.ASCII);

The result is the same for each call to GetStringSha256Hash

03AC674216F3E15C761EE1A5E255F067953623C8B388B4459E13F978D7C846F4

and it is the same as the ascii result from the database.

So my question is, how can I do it in C# do get the unicode result, when I have to start from the value of a simple textBox ?
I just want to make sure that the C# application will never say a value from the DB is not correct because of differences in text encoding.

GuidoG
  • 11,359
  • 6
  • 44
  • 79
  • 4
    "how can I do it in C# do get the unicode result" - have you tried passing in `Encoding.Unicode`? Note that if the text only consists of ASCII characters, UTF-8 and ASCII *should* give the same result.# – Jon Skeet Feb 25 '22 at 09:02
  • 1
    @JonSkeet Well now I am ashamed that I did not see that. Thank you – GuidoG Feb 25 '22 at 09:06

0 Answers0