Obtain SHA-256 string of a string

Dariush Jafari picture Dariush Jafari · Jun 8, 2013 · Viewed 72.8k times · Source

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?

Answer

Dmitry Bychenko picture Dmitry Bychenko · Jun 8, 2013

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

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