Home > Blockchain >  How to calculate sha 512 hash properly in .NET 6
How to calculate sha 512 hash properly in .NET 6

Time:11-28

In .NET 6 code from How can I SHA512 a string in C#?

  var data = Encoding.UTF8.GetBytes("key");
  byte[] hash;
  using (SHA512 shaM = new SHA512Managed())
    hash = shaM.ComputeHash(data);

Throws warning

Warning SYSLIB0021  'SHA512Managed' is obsolete:
'Derived cryptographic types are obsolete.
Use the Create method on the base type instead.'

Visual Studio 2022 does not offer code changes for this. How to replace this code with proper code in .NET 6 ?

Code is called from ASP.NET MVC controller.

CodePudding user response:

In my case I was using RNGCryptoServiceProvider in .NET 5 but when I updated to .NET 6 I got the same warning. After reading about it in this issue I changed my code from this:

public string HashPassword(string plainPassword)
{
    if (string.IsNullOrEmpty(plainPassword))
    {
        throw new ArgumentNullException(nameof(plainPassword));
    }

    var cryptoProvider = new RNGCryptoServiceProvider();
    byte[] salt = new byte[SaltByteSize];
    cryptoProvider.GetBytes(salt);

    byte[] hash = GetPbkdf2Bytes(plainPassword, salt, Pbkdf2Iterations, HashByteSize);

    return $"{Pbkdf2Iterations}:{Convert.ToBase64String(salt)}:{Convert.ToBase64String(hash)}";
}

To this:

public string HashPassword(string plainPassword)
{
    if (string.IsNullOrEmpty(plainPassword))
    {
        throw new ArgumentNullException(nameof(plainPassword));
    }

    byte[] salt = RandomNumberGenerator.GetBytes(SaltByteSize);
    byte[] hash = GetPbkdf2Bytes(plainPassword, salt, Pbkdf2Iterations, HashByteSize);

    return $"{Pbkdf2Iterations}:{Convert.ToBase64String(salt)}:{Convert.ToBase64String(hash)}";
}

I know it's not exactly the same class but they are related.

  • Related