简体   繁体   English

HMAC-SHA1 python使用/生成签名

[英]HMAC-SHA1 python generates signature with /

Given the following 2 base strings: 给定以下2个基本字符串:

GET&https%3A%2F%2Fapi.trademe.co.nz%2Fv1%2FMyTradeMe%2FWatchlist%2Fall.json&oauth_consumer_key%3DE55FD61CBB8400F67CED12FD35761BEDED%26oauth_nonce%3D83236f86429111e3963c0e4586dd63b1%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1383267848%26oauth_token%3D2A378A062E35415E242AD38EA01DE72977%26oauth_version%3D1.0
GET&https%3A%2F%2Fapi.trademe.co.nz%2Fv1%2FMyTradeMe%2FWatchlist%2Fall.json&oauth_consumer_key%3DE55FD61CBB8400F67CED12FD35761BEDED%26oauth_nonce%3D83236f86429111e3963c0e4586dd63b1%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1383267856%26oauth_token%3D2A378A062E35415E242AD38EA01DE72977%26oauth_version%3D1.0

The only difference in those 2 strings is oauth_timestamp, they generate signatures as below: 这两个字符串的唯一区别是oauth_timestamp,它们生成如下的签名:

jBy364dHhQ0kVqYSQePXqyzoDQE=
enKa2bqAgghJNXZxRbTx/2ZQYFI=

What annoys me is second string generates a / in signature, but not first one, causing oauth signatures being incorrect. 令我烦恼的是第二个字符串生成一个/ in签名,但不是第一个,从而导致oauth签名不正确。

This is my python code to generate the signature: 这是我生成签名的python代码:

binascii.b2a_base64(hmac.new('{}&{}'.format(settings.OAUTH_SECRET, oauth_token_secret), base_string, sha1).digest())[:-1]

Your code is working fine. 您的代码运行正常。 / is a valid base64 character, specifically 63. /是有效的base64字符,尤其是63。

If you'd like a different behavior, you can use Python's base64 library 's b64encode method and specify the altchars= argument, for which you can give alternate characters to replace + and / . 如果您希望改变行为,可以使用Python的base64b64encode方法并指定altchars=参数,为此您可以给其替换字符以替换+/

For example, if you want to use the (non-standard!) Modified Base64 for Filenames, you'd specify "+-" as your altchars argument: 例如,如果您想使用(非标准!)修改后的Base64作为文件名,则可以将"+-"指定为altchars参数:

base64.b64encode(hmac.new(...), altchars='+-')

This, however, may not be compatible with any third-party endpoint you choose to use. 但是,这可能与您选择使用的任何第三方端点都不兼容。 You're much better off just sticking with the default if at all possible. 如果可能的话,最好坚持使用默认设置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM