Example #1
0
        /// <summary>
        /// Encodes the given data using the SHA hash algorithm.
        /// </summary>
        /// <param name="data">data to hash</param>
        /// <param name="format">output format</param>
        /// <returns>sha 256 hash</returns>
        public static string GenerateHash(string data, HashStringFormat format = HashStringFormat.Hex)
        {
            data = Arguments.EnsureNotNull(data, nameof(data));

            using var algorithm = SHA256.Create();

            return(Common.Hash(data, algorithm, format));
        }
Example #2
0
        /// <summary>
        /// Hash data
        /// </summary>
        /// <param name="data">data to hash</param>
        /// <param name="algorithm">hash algorthim</param>
        /// <param name="format">output format</param>
        /// <returns>hash of data</returns>
        internal static string Hash(string data, HashAlgorithm algorithm, HashStringFormat format)
        {
            // convert the input text to array of bytes
            var hashData = algorithm.ComputeHash(Encoding.Default.GetBytes(data));

            // create new instance of StringBuilder to save hashed data
            var returnValue = new StringBuilder();

            string?stringFormat = format switch
            {
                HashStringFormat.Hex => "x2",
                HashStringFormat.Base64 => throw new NotImplementedException(),
                      _ => throw new InvalidOperationException($"unexpected hash format:{format}"),
            };

            // loop for each byte and add it to StringBuilder
            for (int i = 0; i < hashData.Length; i++)
            {
                returnValue.Append(hashData[i].ToString(stringFormat, CultureInfo.InvariantCulture));
            }

            // return hashed string
            return(returnValue.ToString().ToUpperInvariant());
        }