How can I hash something using MD5 or SHA3_512 algorithm from default System.Security.Cryptography namespace?

103 Views Asked by At

I tried to use HashAlgorithm.Create() to initialize my hashing algorithm, but I get PlatformNotSupportedException when I try to run it.

I also tried just initializing HashAlgorithms with new MD5(); but it obviously didn't work since MD5 and other HashAlgorithms are abstract classes.

Documentation states that HashAlgorithm.Create() is obsolete and won't work anymore, but all code samples still use this method with no alternative provided.

https://learn.microsoft.com/en-US/dotnet/api/system.security.cryptography.hashalgorithm.create?view=net-8.0 https://learn.microsoft.com/en-US/dotnet/core/compatibility/unsupported-apis

I would expect line private readonly SHA3_512 _sha3_512 = SHA3_512.Create(); to not throw PlatformNotSupportedException, especially since SHA3_512 class was added in .NET 8

1

There are 1 best solutions below

0
On

It's not obvious, but you can use rfc2898derivebytes to perform this operation.

byte[] CreateHash(string clearText, byte[] salt, int workFactor, int hashSize)
{
    var hasher = new Rfc2898DeriveBytes
    (
        password: clearText,
        salt: salt,
        iterations: workFactor,
        hashAlgorithm: HashAlgorithmName.SHA512
    );
    return hasher.GetBytes(hashSize);
}