如何C#使用HMAC-SHA1算法

1、HMACSHA1的概念
HMACSHA1 是
从 SHA1 哈希函数构造的一种键控哈希算法,被用作 HMAC(基于哈希的消息验证代码)。此 HMAC
进程将密钥与消息数据混合,使用哈希函数对混合结果进行哈希计算,将所得哈希值与该密钥混合,然后再次应用哈希函数。输出的哈希值长度为 160

位,可以转换为指定位数。

2、QQ OAuth 1.0中用到的哈希算法

/// <summary>

/// HMACSHA1算法加密并返回ToBase64String

/// </summary>

/// <param name="strText">签名参数字符串</param>

/// <param name="strKey">密钥参数</param>

/// <returns>返回一个签名值(即哈希值)</returns>

public static string ToBase64hmac(string strText, string strKey)

{

HMACSHA1 myHMACSHA1 = new HMACSHA1(Encoding.UTF8.GetBytes(strKey));

byte[] byteText = myHMACSHA1.ComputeHash(Encoding.UTF8.GetBytes(strText));

return System.Convert.ToBase64String(byteText);

}
或者写成,原理一样:

public static string HMACSHA1Text(string EncryptText, string EncryptKey)
{
//HMACSHA1加密
string message;
string key;
message = EncryptText;
key = EncryptKey;

System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
byte[] keyByte = encoding.GetBytes(key);
HMACSHA1 hmacsha1 = new HMACSHA1(keyByte);
byte[] messageBytes = encoding.GetBytes(message);
byte[] hashmessage = hmacsha1.ComputeHash(messageBytes);

return ByteToString(hashmessage);
}

前面都注释了参数含义,就不再说明了。COPY就可使用

注明:页面请引用
using System.Security.Cryptography;

3、介绍另外一种HMACSHA1算法的写法

public static string HMACSHA1Text(string EncryptText, string EncryptKey)

{
//HMACSHA1加密
HMACSHA1 hmacsha1 = new HMACSHA1();
hmacsha1.Key = System.Text.Encoding.UTF8.GetBytes(EncryptKey);

byte[] dataBuffer = System.Text.Encoding.UTF8.GetBytes(EncryptText);
byte[] hashBytes = hmacsha1.ComputeHash(dataBuffer);
return Convert.ToBase64String(hashBytes);
}
或者另外一种
public static string HmacSha1Sign(string text, string key)
        {
            Encoding encode = Encoding.GetEncoding(input_charset);
            byte[] byteData = encode.GetBytes(text);
            byte[] byteKey = encode.GetBytes(key);
            HMACSHA1 hmac = new HMACSHA1(byteKey);
            CryptoStream cs = new CryptoStream(Stream.Null, hmac, CryptoStreamMode.Write);
            cs.Write(byteData, 0, byteData.Length);
            cs.Close();
            return Convert.ToBase64String(hmac.Hash);
        }


猜你喜欢

转载自blog.csdn.net/lixiaoer757/article/details/80165429
今日推荐