Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate sha 512 hash properly in .NET 6

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.

like image 561
Andrus Avatar asked Nov 17 '25 03:11

Andrus


2 Answers

    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;
        }
    }
like image 150
Sike Mullivan Avatar answered Nov 18 '25 21:11

Sike Mullivan


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);
    }
}
like image 34
Abooraja Rajabpour Avatar answered Nov 18 '25 20:11

Abooraja Rajabpour



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!