James Lin
James Lin

Reputation: 26538

HMAC-SHA1 python generates signature with /

Given the following 2 base strings:

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:

jBy364dHhQ0kVqYSQePXqyzoDQE=
enKa2bqAgghJNXZxRbTx/2ZQYFI=

What annoys me is second string generates a / in signature, but not first one, causing oauth signatures being incorrect.

This is my python code to generate the signature:

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

Upvotes: 0

Views: 263

Answers (1)

Christian Ternus
Christian Ternus

Reputation: 8492

Your code is working fine. / is a valid base64 character, specifically 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 /.

For example, if you want to use the (non-standard!) Modified Base64 for Filenames, you'd specify "+-" as your altchars argument:

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.

Upvotes: 1

Related Questions