namespace CrazyStudio.Core.CryptHelper
{
    public static class SHA1Crypt
    {
        /// <summary>
        /// 返回输入字符串的SHA1散列值
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static string SHA1HashString(string input)
        {
            SHA1 algorithm = SHA1.Create();
            byte[] data = algorithm.ComputeHash(Encoding.UTF8.GetBytes(input));
            string sh1 = "";
            for (int i = 0; i < data.Length; i++)
            {
                sh1 += data[i].ToString("x2");//.ToUpperInvariant();
            }
            return sh1;
        }


        /// <summary>  
        /// 使用utf8编码将字符串散列  
        /// </summary>  
        /// <param name="sourceString">要散列的字符串</param>  
        /// <returns>散列后的字符串</returns>  
        public static string HashString(string sourceString)
        {
            return HashString(Encoding.UTF8, sourceString);
        }

        /// <summary>  
        /// 使用指定的编码将字符串散列  
        /// </summary>  
        /// <param name="encode">编码</param>  
        /// <param name="sourceString">要散列的字符串</param>  
        /// <returns>散列后的字符串</returns>  
        public static string HashString(Encoding encode, string sourceString)
        {
            MD5 md5 = MD5.Create();
            byte[] source = md5.ComputeHash(encode.GetBytes(sourceString));
            StringBuilder sBuilder = new StringBuilder();
            for (int i = 0; i < source.Length; i++)
            {
                sBuilder.Append(source[i].ToString("x2"));
            }
            return sBuilder.ToString().ToUpper();
        }

        public static string GetHMACSHA256(string message, string secret)
        {
            secret = secret ?? "";
            var encoding = new System.Text.UTF8Encoding();
            byte[] keyByte = encoding.GetBytes(secret);
            byte[] messageBytes = encoding.GetBytes(message);
            using (var hmacsha256 = new HMACSHA256(keyByte))
            {
                byte[] hashmessage = hmacsha256.ComputeHash(messageBytes);
                StringBuilder builder = new StringBuilder();
                for (int i = 0; i < hashmessage.Length; i++)
                {
                    builder.Append(hashmessage[i].ToString("x2"));
                }
                return builder.ToString().ToUpper();
            }
        }
    }
}
