Compute SHA256 Hash In C#

Hashing (also known as hash functions) in cryptography is a process of mapping a binary string of an arbitrary length to a small binary string of a fixed length, known as a hash value, a hash code, or a hash. Hash functions are a common way to protect secure sensitive data such as passwords and digital signatures. Some of the modern commonly-used hash functions are MD5, RIPEMD160, SHA1, SHA256, SHA384, and SHA512.

Hashing is a one-way conversion. You cannot un-hash hashed data.

The NET framework provides cryptography-related functionality encapsulated in System.Security.Cryptography namespace and its classes. The HashAlgorithm class is the base class for hash algorithms including MD5, RIPEMD160, SHA1, SHA256, SHA384, and SHA512.

The ComputeHash method of HashAlgorithm computes a hash. It takes a byte array or stream as an input and returns a hash in the form of a byte array of 256 chars.

  1. byte[] bytes = sha256Hash.ComputeHash(Encoding.UTF8.GetBytes(rawData));  

No matter how big the input data is, the hash will always be 256 chars. The following code snippet is an example of how to create a hash of a string.

  1. using System;  
  2. using System.Text;  
  3. using System.Security.Cryptography;  
  4.   
  5. namespace HashConsoleApp  
  6. {  
  7.     class Program  
  8.     {  
  9.         static void Main(string[] args)  
  10.         {  
  11.             string plainData = "Mahesh";  
  12.             Console.WriteLine("Raw data: {0}", plainData);  
  13.             string hashedData = ComputeSha256Hash(plainData);  
  14.             Console.WriteLine("Hash {0}", hashedData);  
  15.             Console.WriteLine(ComputeSha256Hash("Mahesh"));  
  16.             Console.ReadLine();  
  17.         }  
  18.   
  19.         static string ComputeSha256Hash(string rawData)  
  20.         {  
  21.             // Create a SHA256   
  22.             using (SHA256 sha256Hash = SHA256.Create())  
  23.             {  
  24.                 // ComputeHash - returns byte array  
  25.                 byte[] bytes = sha256Hash.ComputeHash(Encoding.UTF8.GetBytes(rawData));  
  26.   
  27.                 // Convert byte array to a string   
  28.                 StringBuilder builder = new StringBuilder();  
  29.                 for (int i = 0; i < bytes.Length; i++)  
  30.                 {  
  31.                     builder.Append(bytes[i].ToString("x2"));  
  32.                 }  
  33.                 return builder.ToString();  
  34.             }  
  35.         }  
  36.                  
  37.     }  
  38.   
  39. }  

X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now