在python中实现HMAC-SHA1

xia*_*012 41 python sha1 oauth hmac

我正在尝试使用网站的OAuth,这要求签名方法仅为"HMAC-SHA1".

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

Jon*_*der 73

Pseudocodish:

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')
Run Code Online (Sandbox Code Playgroud)

签名错误通常存在于基本字符串中,请确保您理解这一点(如OAuth1.0规范所述:http://tools.ietf.org/html/draft-hammer-oauth-10#section-3.4 . 1).

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

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

    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
    
    Run Code Online (Sandbox Code Playgroud)

连接和URL编码每个部分,最终结果如下:

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

  • 你可以使用`.rstrip('\n')`来代替`[:1]`,如果你想牺牲一些简洁性来明确你正在砍掉一个尾随的换行符. (3认同)
  • 哦,最后一个字符是`\n`,不应该是签名的一部分. (2认同)

Bla*_*g23 17

为了爱上帝,如果你对oauth做任何事情,请使用requestsPython库!我尝试使用hmacPython中的库来实现HMAC-SHA1 ,这很麻烦,尝试创建正确的oauth基本字符串等.只需使用请求,它就像:

>>> import requests
>>> from requests_oauthlib import OAuth1

>>> url = 'https://api.twitter.com/1.1/account/verify_credentials.json'
>>> auth = OAuth1('YOUR_APP_KEY', 'YOUR_APP_SECRET', 'USER_OAUTH_TOKEN', 'USER_OAUTH_TOKEN_SECRET')

>>> requests.get(url, auth=auth)
Run Code Online (Sandbox Code Playgroud)

请求身份验证

请求Oauth图书馆

  • 经过两天的搜索,我的api调用有什么问题的解决方案(http://stackoverflow.com/questions/39164472/verification-of-signature-failed-oauth-1-upwork-api),我终于用了你的把戏然后继续前进 (2认同)

Raf*_*ael 6

最后,这是一个使用oauthlib的实际工作解决方案(使用 Python 3 测试)。

我使用官方 RTF 1 中给出的第一个 OAuth 步骤作为示例:

Client Identifier: dpf43f3p2l4k3l03
Client Shared-Secret: kd94hf93k423kf44

POST /initiate HTTP/1.1
Host: photos.example.net
Authorization: OAuth realm="Photos",
    oauth_consumer_key="dpf43f3p2l4k3l03",
    oauth_signature_method="HMAC-SHA1",
    oauth_timestamp="137131200",
    oauth_nonce="wIjqoS",
    oauth_callback="http%3A%2F%2Fprinter.example.com%2Fready",
    oauth_signature="74KNZJeDHnMBp0EMJ9ZHt%2FXKycU%3D"
Run Code Online (Sandbox Code Playgroud)

的值oauth_signature是我们想要计算的值。

以下定义了我们要签名的内容:

# There is no query string present.
# In case of http://example.org/api?a=1&b=2 - the value
# would be "a=1&b=2".
uri_query=""

# The oauthlib function 'collect_parameters' automatically
# ignores irrelevant header items like 'Content-Type' or
# 'oauth_signature' in the 'Authorization' section.
headers={
    "Authorization": (
        'OAuth realm="Photos", '
        'oauth_nonce="wIjqoS", '
        'oauth_timestamp="137131200", '
        'oauth_consumer_key="dpf43f3p2l4k3l03", '
        'oauth_signature_method="HMAC-SHA1", '
        'oauth_callback="http://printer.example.com/ready"'
    )
}

# There's no POST data here - in case it was: x=1 and y=2,
# then the value would be '[("x","1"),("y","2")]'.
data=[]

# This is the above specified client secret which we need
# for calculating the signature.
client_secret="kd94hf93k423kf44"
Run Code Online (Sandbox Code Playgroud)

现在我们开始:

import oauthlib.oauth1.rfc5849.signature as oauth

params = oauth.collect_parameters(
    uri_query="",
    body=data, 
    headers=headers,
    exclude_oauth_signature=True, 
    with_realm=False
)

norm_params = oauth.normalize_parameters(params)

base_string = oauth.construct_base_string(
    "POST", 
    "https://photos.example.net/initiate", 
    norm_params
)

sig = oauth.sign_hmac_sha1(
    base_string, 
    client_secret, 
    '' # resource_owner_secret - not used
)
Run Code Online (Sandbox Code Playgroud)
from urllib.parse import quote_plus

print(sig)
# 74KNZJeDHnMBp0EMJ9ZHt/XKycU=

print(quote_plus(sig))
# 74KNZJeDHnMBp0EMJ9ZHt%2FXKycU%3D
Run Code Online (Sandbox Code Playgroud)


Qy *_*Zuo 6

你可以试试下面的方法。

def _hmac_sha1(input_str):
        raw = input_str.encode("utf-8")
        key = 'your_key'.encode('utf-8')
        hashed = hmac.new(key, raw, hashlib.sha1)
        return base64.encodebytes(hashed.digest()).decode('utf-8')
Run Code Online (Sandbox Code Playgroud)