Xamarin PCLCrypto SHA256 give different hash

2019-07-21 06:25发布

问题:

I have a project in Xamarin Forms XAML portable. i need to get a SHA256 from a string. I use the PCLCrypto for finding my hash, because System.Security.Cryptography doesn't exist in PCL.

I get a sha256 from an API to compare the values. This is the method I use to get the SHA256 hash:

private string getSha256(string data) {
            byte[] byteData = Encoding.UTF8.GetBytes(data);
            var hasher = WinRTCrypto.HashAlgorithmProvider.OpenAlgorithm(HashAlgorithm.Sha256);
            byte[] hash = hasher.HashData(byteData);
            string hashBase64 = Convert.ToBase64String(hash);
            return hashBase64;
        }

The string I use is 'secret'. I use this to check it:

http://www.xorbin.com/tools/sha256-hash-calculator and it gives:

2bb80d537b1da3e38bd30361aa855686bde0eacd7162fef6a25fe97bf527a25b

But I'm getting two different hash codes:

API hash: 2bb80d537b1da3e38bd30361aa855686bde0eacd7162fef6a25fe97bf527a25b

PCLCrypto hash I generated: K7gNU3sdo+OL0wNhqoVWhr3g6s1xYv72ol/pe/Unols=

Its the same string 'secret' but is resulting in different hashes. I also noticed PCLCrypto hash always ends with '='.

Why are they different?

回答1:

If you use a converter like http://hash.online-convert.com/sha256-generator you'll see that the two hashes are the same (enter 'secret' in the Text box and click on Convert File).

The '2bb80...' string is the hex encoding of the hash, and the 'K7gNU...' string is the base64 encoding of the hash (which is what you asked for in your call to PCLCrypto). The issue is that the hash itself is binary data, so to display it you need some conversion to string. You're seeing two common ways to do that, both using the same underlying hash.