C# HashHelpers

Date: 2016-03-19
using System.Text;
using System.Security.Cryptography;

namespace Domain.Helpers
{
    /// Class contains short hands for widely used hash algoritms
    public class HashHelpers
    {
        public static string GetMD5(string data) => GetHash(MD5.Create(), data);
        public static string GetSHA1(string data) => GetHash(SHA1.Create(), data);
        public static string GetSHA256(string data) => GetHash(SHA256.Create(), data);
        public static string GetSHA384(string data) => GetHash(SHA384.Create(), data);
        public static string GetSHA512(string data) => GetHash(SHA512.Create(), data);

        public static string GetSHA1Guid(string data)
        {
            // SHA1 = 2fd4e1c67a2d28fced849ee1bb76e7391b93eb12
            // Guid = {3f2504e0-4f89-11d3-9a0c-0305e82c3301}
            string sha1 = GetSHA1(data);
            string[] parts = new string[] {
                sha1.Substring(0,8),
                sha1.Substring(8,4),
                sha1.Substring(12,4),
                sha1.Substring(16,4),
                sha1.Substring(20,12)
            };
            return string.Join("-", parts);
        }
        ///
        /// Get hash as string from string data
        /// 
        ///Data which is hashed with algoritm
        /// hash as string
        public static string GetHash(HashAlgorithm algoritm, string data)
        {
            byte[] inputBytes = Encoding.UTF8.GetBytes(data);
            byte[] hashBytes = algoritm.ComputeHash(inputBytes);
            // Convert the byte array to hexadecimal string
            var sb = new StringBuilder();
            for (int i = 0; i < hashBytes.Length; i++)
            {
                sb.Append(hashBytes[i].ToString("x2")); // For uppercase use: X2
            }
            return sb.ToString();
        }
    }
}
1170cookie-checkC# HashHelpers