认识OAuth签名使用的HMACSHA1哈希算法

来源:互联网 发布:海岛奇兵所有升级数据 编辑:程序博客网 时间:2024/04/29 04:01

开始着手QQ OAuth1.0 接口的开发,第一步是请求临时未授权的Request Token,而其中用了一个关键的加密算法-HMACSHA1哈希算法,弄的我有点糊涂,所以查了一些文章,了解了这个算法,且不深入研究这种算法,在NET中我们直接拿来用即可,下面只是讲解认识HMACSHA1在OAuth中签名的使用:

1、HMACSHA1的概念
HMACSHA1 是从 SHA1 哈希函数构造的一种键控哈希算法,被用作 HMAC(基于哈希的消息验证代码)。此 HMAC 进程将密钥与消息数据混合,使用哈希函数对混合结果进行哈希计算,将所得哈希值与该密钥混合,然后再次应用哈希函数。输出的哈希值长度为 160 位,可以转换为指定位数。
上面是微软的标准定义,我看了也没太明白,他的作用一句话来理解:就是确认请求的URL或者参数是否存在被篡改,以QQ签名为例:发送方(自己)将参数等进行HMAC算法计算,将得到的哈希值(即签名值)与请求的参数一同提交至接收方(QQ端),然后接收方再次将参数等值进行HMAC算法计算,将得到的哈希值与你传递过来的哈希值进行核对验证,若一样,说明请求正确、验证通过,进行一下步工作,若不一样,将返回错误。 (下面说的够详细了吧,还不理解,留言给我)

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);
 }

原创粉丝点击