Quantcast
Channel: Brian Pedersen's Sitecore and .NET Blog
Viewing all articles
Browse latest Browse all 285

C# ‘SHA256Managed’ is obsolete: ‘Derived cryptographic types are obsolete. Use the Create method on the base type instead.’

$
0
0

So my code gives me this warning:

Warning SYSLIB0021  ‘SHA256Managed’ is obsolete: ‘Derived cryptographic types are obsolete. Use the Create method on the base type instead.’

The code that warns me are:

using System.Text;
using System.Security.Cryptography;

public static string ToSHA256(string s)
{
  SHA256Managed sha256 = new SHA256Managed();
  StringBuilder hash = new StringBuilder();
  byte[] hashArray = sha256.ComputeHash(Encoding.UTF8.GetBytes(s));
  foreach (byte b in hashArray)
  {
    hash.Append(b.ToString("x"));
  }
  return hash.ToString();
}

The reason is that SHA256Managed, SHA512Managed, SHA1Managed and SHA384Managed have all been deprecated, and replaced with SHA256, SHA512, SHA1 and SHA384.

To replace the SHAxxxManaged class with the new counterpart, you can do this instead:

using System.Text;
using System.Security.Cryptography;

public static string ToSHA256(string s)
{
  using (SHA256 sha256 = SHA256.Create())
  {
    StringBuilder hash = new StringBuilder();
    byte[] hashArray = sha256.ComputeHash(Encoding.UTF8.GetBytes(s));
    foreach (byte b in hashArray)
    {
      hash.Append(b.ToString("x"));
    }
    return hash.ToString();
  }
}

Both methods return the same result:

using System;
using System.Text;
using System.Security.Cryptography;
					
public class Program
{
  public static void Main()
  {	
    string s = "https://briancaos.wordpress.com";
    Console.WriteLine(SHA256_Old(s));
  	Console.WriteLine(SHA256_New(s));
	// Output is:
	// 94511e66dd13c5195f32930928d76455b76c53541b499dd2d1b3b5cf03cf498
    // 94511e66dd13c5195f32930928d76455b76c53541b499dd2d1b3b5cf03cf498
  }

  // Deprecated version, do not use in .net core 6 and newer
  private static string SHA256_Old(string s)
  {
    SHA256Managed sha256 = new SHA256Managed();
    StringBuilder hash = new StringBuilder();
    byte[] hashArray = sha256.ComputeHash(Encoding.UTF8.GetBytes(s));
    foreach (byte b in hashArray)
    {
      hash.Append(b.ToString("x"));
    }
    return hash.ToString();
  }
	  
  // New version for .net core 6 and newer
  private static string SHA256_New(string s)
  {
    var byteString = Encoding.UTF8.GetBytes("key");
    using (SHA256 sha256 = SHA256.Create())
    {
	  StringBuilder hash = new StringBuilder();
      byte[] hashArray = sha256.ComputeHash(Encoding.UTF8.GetBytes(s));
      foreach (byte b in hashArray)
      {
        hash.Append(b.ToString("x"));
      }
      return hash.ToString();
    }
  }
}

That’s it. You are now a cryptography expert. Happy coding.

MORE TO READ:


Viewing all articles
Browse latest Browse all 285

Trending Articles