Question

In a legacy system we have a password made by the following in SQL Server.

select HashBytes('SHA1' , Convert(nvarchar(4000),'MyPassword'))

Now, cause a lot of non-functional requirements, we have to compute the same password in C#.

My best try was:

public static byte[] CalculateSHA1(string text)
{
    byte[] buffer = UTF8Encoding.Default.GetBytes(text);
    SHA1CryptoServiceProvider cryptoTransformSHA1 = new SHA1CryptoServiceProvider();
    return cryptoTransformSHA1.ComputeHash(buffer);
}

But it returns a different array of bytes than the SQL Code returns.

Someone could help me?

Was it helpful?

Solution

Change UTF8Encoding.Default to Encoding.Unicode and the results will match. SQL Server HashBytes function uses UTF16 when converting NCHARs and NVARCHARs to bytes before performing the actual hash.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top