在python中实现HMAC-SHA1 [英] Implementation HMAC-SHA1 in python

查看:1148
本文介绍了在python中实现HMAC-SHA1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用网站的OAuth,该网站要求签名方法仅是'HMAC-SHA1'.

I am trying to use the OAuth of a website, which requires the signature method to be 'HMAC-SHA1' only.

我想知道如何在Python中实现它?

I am wondering how to implement this in Python?

推荐答案

假博士:

def sign_request():
    from hashlib import sha1
    import hmac

    # key = b"CONSUMER_SECRET&" #If you dont have a token yet
    key = b"CONSUMER_SECRET&TOKEN_SECRET" 


    # The Base String as specified here: 
    raw = b"BASE_STRING" # as specified by OAuth

    hashed = hmac.new(key, raw, sha1)

    # The signature
    return hashed.digest().encode("base64").rstrip('\n')

签名错误通常位于基本字符串中,请确保您理解这一点(如OAuth1.0规范在此处所述:

Signature errors usually reside in the base-string, make sure you understand this (as stated by the OAuth1.0 spec here: http://tools.ietf.org/html/draft-hammer-oauth-10#section-3.4.1).

以下输入用于生成签名基本字符串:

The following inputs are used to generate the Signature Base String:

  1. HTTP方法(例如GET)
  2. 路径(例如 http://photos.example.net/photos )
  3. 按字母顺序排列的参数,例如(换行符以提高可读性):

  1. HTTP Method (for example GET)
  2. Path (for example http://photos.example.net/photos)
  3. Parameters, alphabetically, such as (line breaks for readability):

file=vacation.jpg
&oauth_consumer_key=dpf43f3p2l4k3l03
&oauth_nonce=kllo9940pd9333jh
&oauth_signature_method=HMAC-SHA1
&oauth_timestamp=1191242096
&oauth_token=nnch734d00sl2jdk
&oauth_version=1.0
&size=original

串联并用URL编码每个部分,最终结果为:

Concatenate and URL encode each part and it ends up as:

GET&http%3A%2F%2Fphotos.example.net%2Fphotos&file%3Dvacation.jpg%26 oauth_consumer_key%3Ddpf43f3p2l4k3l03%26oauth_nonce%3Dkllo9940pd9333jh%26 oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1191242096%26 oauth_token%3Dnnch734d00sl2jdk%26oauth_version%3D1.0%26size%3Doriginal

GET&http%3A%2F%2Fphotos.example.net%2Fphotos&file%3Dvacation.jpg%26 oauth_consumer_key%3Ddpf43f3p2l4k3l03%26oauth_nonce%3Dkllo9940pd9333jh%26 oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1191242096%26 oauth_token%3Dnnch734d00sl2jdk%26oauth_version%3D1.0%26size%3Doriginal

这篇关于在python中实现HMAC-SHA1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆