SQL Server HASHBYTES SHA2_512 and C#
c#, encryption, sql-server, sqlclr
Solution
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;
}
Problem
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; } ```