Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server HASHBYTES SHA2_512 and C#

If I run the following in SQL Server:

SELECT HASHBYTES('SHA2_512', 'THE CAT SAT ON THE MAT')

and then run this in C#

string test = WordFunctions.SHA512("THE CAT SAT ON THE MAT");

I get the same value back for both which is great. However, if I pass a string variable in my C# code so something like this:

string words = "THE CAT SAT ON THE MAT"

byte[] test
test = WordFunctions.SHA512(words);

then I don't get the same value?!

Any ideas?

the SHA512 function looks like this:

public static byte[] SHA512(String plaintext)
{
   // convert the passPhrase string into a byte array
   ASCIIEncoding AE = new ASCIIEncoding();
   byte[] passBuff = AE.GetBytes(plaintext);

   SHA512Managed hashVal = new SHA512Managed();
   byte[] passHash = hashVal.ComputeHash(passBuff);

   return passHash;
}
like image 287
Abu Dina Avatar asked Oct 22 '22 14:10

Abu Dina


1 Answers

The following code worked for me :

private static readonly Encoding Encoding1252 = Encoding.GetEncoding(1252);

public static byte[] SHA1HashValue(string s)
{
    byte[] bytes = Encoding1252.GetBytes(s);

    var sha1 = SHA512.Create();
    byte[] hashBytes = sha1.ComputeHash(bytes);

    return hashBytes;
}
like image 96
user2633318 Avatar answered Oct 27 '22 22:10

user2633318