SHA-256(Source Code in C# using .Net in-built Cryptography library) – Part II

.Net Framework provides in built support for various hash functions like MD-5, SHA-1, SHA-256 etc…   ComputeHash method Computes the hash value to the specified byte array.  

Below are the overloaded methods to Compute Hash using SHA-256 class in System.Security.Cryptography  library  

public byte[] ComputeHash(byte[] buffer)
public byte[] ComputeHash(Stream inputStream)  
public byte[] ComputeHash(byte[] buffer, int offset, int count)    

 

Here is C# source code using .Net In-build library

using System;
using System.Security.Cryptography;
using System.Text;

namespace SecureHashingProject
{
    public class SecureHashingAlgorithm256
    {
        static void Main()
        {
            var data = Console.ReadLine();
            if (string.IsNullOrEmpty(data))
            {
                Console.WriteLine("No data to generate hash");
                return;
            }

            var sha256 = SHA256.Create();
            var bytes = sha256.ComputeHash(Encoding.UTF8.GetBytes(data));
            var builder = new StringBuilder();
            foreach (var b in bytes)
            {
                builder.Append(b.ToString("x2"));
            }

            Console.WriteLine($"Hash: {builder}");
            Console.ReadLine();
        }
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *