Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Obtain SHA-256 string of a string

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?

like image 633
Dariush Jafari Avatar asked Jun 08 '13 12:06

Dariush Jafari


People also ask

What is a SHA256 string?

A cryptographic hash (sometimes called 'digest') is a kind of 'signature' for a text or a data file. SHA-256 generates an almost-unique 256-bit (32-byte) signature for a text. See below for the source code. Enter any message to check its SHA-256 hash.

How do I know if my string is SHA256?

The only way to check if a hash is a valid SHA-256 hash is to check 256 bits in it- if it does, then yes some input CAN possibly generate that output. Hashes are one way meaning I can give you a hash and you can never decrypt it (this is the difference between hashing and an encryption).

How do I hash a string in C#?

Getting the hash code of a string is simple in C#. We use the GetHashCode() method. A hash code is a uniquely identified numerical value. Note that strings that have the same value have the same hash code.


2 Answers

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();
}
like image 129
Dmitry Bychenko Avatar answered Oct 13 '22 14:10

Dmitry Bychenko


From .NET 5 onwards, you can use the new Convert.ToHexString method to convert the hash byte array into a (hex) string without having to use a StringBuilder or .ToString("X0"), etc.:

public static string HashWithSHA256(string value)
{
  using var hash = SHA256.Create();
  var byteArray = hash.ComputeHash(Encoding.UTF8.GetBytes(value));
  return Convert.ToHexString(byteArray);
}
like image 22
Samuel Johnson Avatar answered Oct 13 '22 15:10

Samuel Johnson