Created
January 26, 2017 02:36
-
-
Save baskaufs/bb392688371cf97625af4760494816fd to your computer and use it in GitHub Desktop.
Fixed function to generate OAuth signature using HMAC-SHA1 hashing algorithm in Python 3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# HMAC-SHA1 hashing algorithm to generate the OAuth signature | |
# using code hacked from https://gist.github.com/binaryatrocity/7079332cab038da1394d | |
from base64 import b64encode # needed for create_signature function | |
import hmac # needed for create_signature function | |
import hashlib | |
import binascii | |
# here's the first function hacked from the binaryatrocity GIST: | |
def create_signature(secret_key, string): | |
""" Create the signed message from api_key and string_to_sign """ | |
string_to_sign = string.encode('utf-8') | |
# in the example, the secret_key wasn't encoded, but I got an error message without encoding it | |
encoded_key = secret_key.encode('utf-8') | |
# there were a number of things that were different from Python2 to Py3 | |
# but I think this is right | |
temp = hmac.new(encoded_key, string_to_sign, hashlib.sha1).hexdigest() | |
# temp represents the binary number in hexadecimal using string characters | |
# it has to be converted into an actual binary number using the unhexlify function. | |
# output is in byte array format | |
byte_array = b64encode(binascii.unhexlify(temp)) | |
# convert the byte array to UTF-8 characters using the decode function | |
return byte_array.decode("utf-8") | |
# Here are the example secret keys from https://dev.twitter.com/oauth/overview/creating-signatures | |
signing_key = 'kAcSOqF21Fu85e7zjz7ZN2U4ZRhfV3WpwPAoE3Z7kBw&LswwdoUaIvS8ltyTt5jkRh4J50vUPVVHtR2YPi5kE' | |
signature_base_string = 'POST&https%3A%2F%2Fapi.twitter.com%2F1%2Fstatuses%2Fupdate.json&include_entities%3Dtrue%26oauth_consumer_key%3Dxvz1evFS4wEEPTGEFPHBog%26oauth_nonce%3DkYjzVBB8Y0ZFabxSWbWovY3uYSQ2pTgmZeNu2VS4cg%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1318622958%26oauth_token%3D370773112-GmHxMAgYyLbNEtIKZeRNFsMKPR9EyMZeS9weJAEb%26oauth_version%3D1.0%26status%3DHello%2520Ladies%2520%252B%2520Gentlemen%252C%2520a%2520signed%2520OAuth%2520request%2521' | |
sig_string = create_signature(signing_key, signature_base_string) | |
print (sig_string) | |
# the answer now agrees with the example OAuth signature: 'tnnArxj06cWHq44gCs1OSKk/jLY=' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I
collect
the create_signature function