Obtain SHA-256 string of a string

C#StringHashSha256

C# Problem Overview


I have some string and I want to hash it with the SHA-256 hash function using C#. I want something like this:

 string hashString = sha256_hash("samplestring");

Is there something built into the framework to do this?

C# Solutions


Solution 1 - C#

The implementation could be like that

public static String sha256_hash(String value) {
  StringBuilder Sb = new StringBuilder();

  using (SHA256 hash = SHA256Managed.Create()) {
    Encoding enc = Encoding.UTF8;
    Byte[] result = hash.ComputeHash(enc.GetBytes(value));

    foreach (Byte b in result)
      Sb.Append(b.ToString("x2"));
  }

  return Sb.ToString();
}

Edit: Linq implementation is more concise, but, probably, less readable:

public static String sha256_hash(String value) {
  using (SHA256 hash = SHA256Managed.Create()) {
    return String.Concat(hash
      .ComputeHash(Encoding.UTF8.GetBytes(value))
      .Select(item => item.ToString("x2")));
  }
} 

Edit 2: .NET Core , .NET5, .NET6 ...

public static String sha256_hash(string value)
{
    StringBuilder Sb = new StringBuilder();

    using (var hash = SHA256.Create())            
    {
        Encoding enc = Encoding.UTF8;
        byte[] result = hash.ComputeHash(enc.GetBytes(value));

        foreach (byte b in result)
            Sb.Append(b.ToString("x2"));
    }

    return Sb.ToString();
}

Solution 2 - C#

This is a much nicer/neater way in .net core:

public static string sha256_hash( string value )
{
  using var hash = SHA256.Create();
  var byteArray = hash.ComputeHash( Encoding.UTF8.GetBytes( value ) );
  return Convert.ToHexString( byteArray ).ToLower();
}

Solution 3 - C#

I was looking for an in-line solution, and was able to compile the below from Dmitry's answer:

public static String sha256_hash(string value)
{
    return (System.Security.Cryptography.SHA256.Create()
            .ComputeHash(Encoding.UTF8.GetBytes(value))
            .Select(item => item.ToString("x2")));
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDariush JafariView Question on Stackoverflow
Solution 1 - C#Dmitry BychenkoView Answer on Stackoverflow
Solution 2 - C#Samuel JohnsonView Answer on Stackoverflow
Solution 3 - C#aaronsteersView Answer on Stackoverflow