How to hash a string with SHA-256 in C#

1 Answer

0 votes
using System;
using System.Security.Cryptography;
using System.Text;

class Program
{
    static void Main()
    {
        string input = "C# programming language";
        string hash = ComputeSha256(input);
        Console.WriteLine(hash);
    }

    // Reusable function that returns SHA‑256 hash as a hex string
    public static string ComputeSha256(string input) 
    {
        using SHA256 sha = SHA256.Create();

        byte[] bytes = Encoding.UTF8.GetBytes(input);
        byte[] hashBytes = sha.ComputeHash(bytes);

        StringBuilder sb = new StringBuilder();
        foreach (byte b in hashBytes) {
            sb.Append(b.ToString("x2"));
        }

        return sb.ToString();
    }
}



/*
run:

4b0ee8719062c6a9713c87f328e57009e18007cbfef02648ff9d72036f5dacf3

*/

 



answered 11 hours ago by avibootz
...