'How to hash string in Blazor wasm?

In Net 5 Blazor client webassembly I can not use System.Security.Cryptography to compute SHA512. What are working alternatives? So that some text hashed has the same hash on all browsers?



Solution 1:[1]

I played around with blazor recently, and ran into this issue as well.

Sadly, the answer I found was this:

https://docs.microsoft.com/en-us/dotnet/core/compatibility/cryptography/5.0/cryptography-apis-not-supported-on-blazor-webassembly

Currently the only workaround I see, is to create an API that does the hashing for you, and then call it using:

https://docs.microsoft.com/en-us/aspnet/core/blazor/call-web-api?view=aspnetcore-5.0&pivots=server

Solution 2:[2]

Code below works in Blazor WASM.

static int GetDeterministicHashCode(this string str)
{
    unchecked
    {
        int hash1 = (5381 << 16) + 5381;
        int hash2 = hash1;

        for (int i = 0; i < str.Length; i += 2)
        {
            hash1 = ((hash1 << 5) + hash1) ^ str[i];
            if (i == str.Length - 1)
                break;
            hash2 = ((hash2 << 5) + hash2) ^ str[i + 1];
        }

        return hash1 + (hash2 * 1566083941);
    }
}

Read this article for more info : https://andrewlock.net/why-is-string-gethashcode-different-each-time-i-run-my-program-in-net-core/

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Philip Jensen
Solution 2 user160357