How to calculate sha 512 hash properly in .NET 6
Asked Answered
U

5

21

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.

Uranalysis answered 25/11, 2021 at 10:34 Comment(2)
Why not as recommended in the warning: SHA512 shaM = SHA512.Create() with System.Security.Cryptography.SHA512?Ellersick
thank you, it removes the warning. You can wrote this as answerUranalysis
A
22
    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;
        }
    }
Arbor answered 14/12, 2021 at 15:45 Comment(2)
What if this answer is improved by using var hex = new StringBuilder(); ?Buddy
Why not use Convert.ToHexString introduced in .NET 5?Decadence
M
9

you can use this method

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);
    }
}
Morelli answered 30/3, 2022 at 4:56 Comment(0)
N
0

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.

Nitrosamine answered 27/11, 2021 at 16:10 Comment(0)
S
-1

You can also based on the description of Microsoft website in this link, use this code:

// Disable the warning.
#pragma warning disable SYSLIB0001

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

// Re-enable the warning.
#pragma warning restore SYSLIB0001
Sternmost answered 8/1, 2022 at 7:1 Comment(0)
E
-1

Same as Sike Mullivan's accepted answer, but just a little shorter:

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

or, alternatively a one-liner:

public string CreateSHA512(string strData) => SHA512.Create().ComputeHash(Encoding.UTF8.GetBytes(strData)).Aggregate("", (current, x) => current + $"{x:x2}");
Emotionalism answered 12/1, 2022 at 12:39 Comment(1)
One-liner is without using. It does not dispose resources on return . Also text variable is undefinedUranalysis

© 2022 - 2024 — McMap. All rights reserved.