天天看點

HMACSha1加密方法

最近開發接口對接方使用hmacsha1來進行加密驗證,特定找了文章檢視。

https://www.cnblogs.com/yhnet/p/12448637.html

hmacsha1在很多簽名計算中都很常用了,基本分為兩種

一種是原始直接傳回字元串,一種是baset64後傳回 

基本使用base64的比較多

原始版本

#region HMACSHA1加密  将二進制資料直接轉為字元串傳回
        /// <summary>
        /// HMACSHA1加密
        /// </summary>
        /// <param name="text">要加密的原串</param>
        ///<param name="key">私鑰</param>
        /// <returns></returns>
        public static string HMACSHA1Text(string text,string key)
        {
            //HMACSHA1加密
            HMACSHA1 hmacsha1 = new HMACSHA1();
            hmacsha1.Key = System.Text.Encoding.UTF8.GetBytes(key);

            byte[] dataBuffer = System.Text.Encoding.UTF8.GetBytes(text);
            byte[] hashBytes = hmacsha1.ComputeHash(dataBuffer);

            var enText = new StringBuilder();
            foreach (byte iByte in hashBytes)
            {
                enText.AppendFormat("{0:x2}", iByte);
            }
            return enText.ToString();
            
        }
        #endregion
           

base64版本

#region HMACSHA1加密  二進制資料轉Base64後再傳回
        /// <summary>
        /// HMACSHA1加密
        /// </summary>
        /// <param name="text">要加密的原串</param>
        ///<param name="key">私鑰</param>
        /// <returns></returns>
        public static string HMACSHA1Base64(string text,string key)
        {
            //HMACSHA1加密
            HMACSHA1 hmacsha1 = new HMACSHA1();
            hmacsha1.Key = System.Text.Encoding.UTF8.GetBytes(key);

            byte[] dataBuffer = System.Text.Encoding.UTF8.GetBytes(text);
            byte[] hashBytes = hmacsha1.ComputeHash(dataBuffer);
            
            return Convert.ToBase64String(hashBytes);
            
        }
        #endregion
           

繼續閱讀