Skip to main content

C# functions for creating a SHA256 or SHA384 hash of a string.

namespace Utils
{
    using System.Security.Cryptography;
    using System.Text;

    public static class HashUtil
    {
        public static string ComputeSha256Hash(string utfData)
        {
            using (var hasher = SHA256.Create())
            {
                var hashBytes = hasher.ComputeHash(Encoding.UTF8.GetBytes(utfData));

                var sb = new StringBuilder();
                for (var i = 0; i < hashBytes.Length; i++)
                {
                    sb.Append(hashBytes[i].ToString("x2"));
                }

                return sb.ToString();
            }
        }

        public static string ComputeSha384Hash(string utfData)
        {
            using (var hasher = SHA384.Create())
            {
                var hashBytes = hasher.ComputeHash(Encoding.UTF8.GetBytes(utfData));

                var sb = new StringBuilder();
                for (var i = 0; i < hashBytes.Length; i++)
                {
                    sb.Append(hashBytes[i].ToString("x2"));
                }

                return sb.ToString();
            }
        }
    }
}