52
votes

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?

3
Hashes work on bytes, not strings. So you first need to choose an encoding that transforms the string into bytes. I recommend UTF-8 for this. - CodesInChaos
Something tells me that people reading this post should also check: stackoverflow.com/questions/4948322/… - Ziezi
I'm curious why this question remains closed. It's a reasonable question with good working answers. Voting to re-open. - Sergey Kalinichenko

3 Answers

137
votes

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

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

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