0

I try to rewrite the following C# method to SQL Server 2014 code. So far to no avail.

public static string GetHash(string input)
{
    HashAlgorithm hashAlgorithm = new SHA256CryptoServiceProvider();

    byte[] byteValue = System.Text.Encoding.UTF8.GetBytes(input);
    byte[] byteHash = hashAlgorithm.ComputeHash(byteValue);

    return Convert.ToBase64String(byteHash);
}

Especially the encoding to UTF8 gives me trouble.

I appreciate any help.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
rudimenter
  • 3,242
  • 4
  • 33
  • 46
  • 1
    Yes - encoding to UTF-8 will give you trouble, since SQL Server **does not support** UTF-8 ... – marc_s Apr 15 '16 at 09:48

1 Answers1

0

You are not going to be able to do it, unless you can change the encoding of your GetHash method to Unicode.

If you are able to do that, the following should work

public static string GetHash(string input)
        {
            HashAlgorithm hashAlgorithm = new SHA256CryptoServiceProvider();

            byte[] byteValue = System.Text.Encoding.Unicode.GetBytes(input);
            byte[] byteHash = hashAlgorithm.ComputeHash(byteValue);

            return Convert.ToBase64String(byteHash);
        }

Input "testing æøå" output : Rp/BQKVFVjtWxNL9Oj8VGkiS769ekSVYhE9AzlKnvPw=

DECLARE @Bin VARBINARY(MAX);
set @bin = (select HASHBYTES('SHA2_256',N'testing æøå'))

select CAST(N'' AS XML).value('xs:base64Binary(xs:hexBinary(sql:variable("@bin")))','VARCHAR(MAX)')

Input "testing æøå" output : Rp/BQKVFVjtWxNL9Oj8VGkiS769ekSVYhE9AzlKnvPw=

Kaspar Kjeldsen
  • 936
  • 1
  • 13
  • 30