SHA1 Hash not the same between Windows Phone 8.1 app and UWP app

335 Views Asked by At

In Windows Phone 8 I was able to do something like this:

 SHA1Managed s = new SHA1Managed();
 UTF8Encoding enc = new UTF8Encoding();
 s.ComputeHash(enc.GetBytes(password.ToCharArray()));
 string hash = BitConverter.ToString(s.Hash).Replace("-", "").ToLower();

For UWP App I am doing:

IBuffer buffUtf8Msg = CryptographicBuffer.ConvertStringToBinary(password, BinaryStringEncoding.Utf8);

HashAlgorithmProvider objAlgProv = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Sha1);

IBuffer buffHash = objAlgProv.HashData(buffUtf8Msg);

if (buffHash.Length != objAlgProv.HashLength)
{
    throw new Exception("There was an error creating the hash");
}

string strHashBase64 = CryptographicBuffer.EncodeToBase64String(buffHash);

string hash = strHashBase64.Replace("-", "").ToLower();

I am not getting the same result.

For example, if I had the text "Windows 8", I would get

6517856f8c3a3fda3ae28305a05d127f0e1bdb97 (Windows Phone 8.1)

and

zrefb4w6p9o64omfof0sfw4b25c= (UWP)

I dont quite know what I am doing wrong. The goal is to just get the SHA1 hash of a string.

1

There are 1 best solutions below

0
pah On BEST ANSWER

Instead of encoding to base64 under UWP code (CryptographicBuffer.EncodeToBase64String(buffHash)), you probably want to encode to hexadecimal with:

string strHex = CryptographicBuffer.EncodeToHexString(buffHash);
string hash = strHex.ToLower();

So both of your Windows Phone 8 code and UWP code will produce the same output (hex encoded SHA1).