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
#region HMACSHA1加密 對二進制數據轉Base64后再返回 /// <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); return Convert.ToBase64String(hashBytes); } #endregion
