Search code examples
asp.net-mvccryptographyshasha512.net-6.0

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.


Solution

  •     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;
            }
        }