如何在 .NET 6 中正确计算 sha 512 哈希

How to calculate sha 512 hash properly in .NET 6

来自 How can I SHA512 a string in C#?

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

引发警告

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

Visual Studio 2022 不为此提供代码更改。 如何在 .NET 6 中用正确的代码替换此代码?

从 ASP.NET MVC 控制器调用代码。

在我的例子中,我在 .NET 5 中使用 RNGCryptoServiceProvider,但是当我更新到 .NET 6 时,我收到了同样的警告。在 this issue 中阅读了相关内容后,我将代码更改为:

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)}";
}

为此:

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)}";
}

我知道这不完全一样class但它们是相关的。

    public string CreateSHA512(string strData)
    {
        var message = Encoding.UTF8.GetBytes(strData);
        using (var alg = SHA512.Create())
        {
            string hex = "";

            var hashValue = alg.ComputeHash(message);
            foreach (byte x in hashValue)
            {
                hex += String.Format("{0:x2}", x);
            }
            return hex;
        }
    }

您也可以根据this link中微软网站的描述, 使用此代码:

// Disable the warning.
#pragma warning disable SYSLIB0001

// Code that uses obsolete API.
//...

// Re-enable the warning.
#pragma warning restore SYSLIB0001

与 Sike Mullivan 接受的答案相同,但更短:

    public string CreateSHA512(string strData)
    {
        var message = Encoding.UTF8.GetBytes(strData);
        using var alg = SHA512.Create();

        var hashValue = alg.ComputeHash(message);
        return hashValue.Aggregate("", (current, x) => current + $"{x:x2}");
    }

或者,或者单行:

public string CreateSHA512(string strData) => SHA512.Create().ComputeHash(Encoding.UTF8.GetBytes(strData)).Aggregate("", (current, x) => current + $"{x:x2}");

你可以用这个方法

public string GetSha256Hash(string input)
{
    using (var hashAlgorithm = SHA512.Create())
    {
        var byteValue = Encoding.UTF8.GetBytes(input);
        var byteHash = hashAlgorithm.ComputeHash(byteValue);
        return Convert.ToBase64String(byteHash);
    }
}