#SQL Hashbytes compatible code in C#
The SQL function hashbytes allows you to hash strings directly in the database; by using something such as;
select hashbytes(‘MD5′,’hello world’)
which returns 0x5EB63BBBE01EEED093CB22BB8F5ACDC3
But if you want to compare this string with a hash created on the server by C#, then you’ll need to get it into the right format – where you could use this code here:
public static string HashBytes(string valueToHash)
{
HashAlgorithm hasher = new MD5CryptoServiceProvider();
Byte[] valueToHashAsByte = Encoding.UTF8.GetBytes(String.Concat(valueToHash, SaltValue));
Byte[] returnBytes = hasher.ComputeHash(valueToHashAsByte);
StringBuilder hex = new StringBuilder(returnBytes.Length * 2);
foreach (byte b in returnBytes) hex.AppendFormat(“{0:x2}”, b);
return “0x” + hex.ToString().ToUpper();
}