Skip to content

Instantly share code, notes, and snippets.

@realFranco
Last active July 1, 2022 12:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save realFranco/63b678b3fbf6c24e8c59409cd903f731 to your computer and use it in GitHub Desktop.
Save realFranco/63b678b3fbf6c24e8c59409cd903f731 to your computer and use it in GitHub Desktop.
OAuth 1a - Appendix A.5.1. Generating Signature Base String - Implementation in Python #python #oauth #sha1
"""
Github @realFranco
Testing OAuth1a
"""
def test_compose_oauth1a_signature() -> None:
"""
Reference: https://oauth.net/core/1.0/#sig_base_example
DISCLAIMER: Keys | data exposed coming from oauth.net/core/1.0
This function will test oauth signature generation, through the next steps:
- normalize request parameters
- create sign key
- ceate base string
- generate key using sha1 be default or the required by the client (sha256 for example)
"""
expected_base_string = 'GET&http%3A%2F%2Fphotos.example.net%2Fphotos&file%3Dvacation.jpg%26oauth_consumer_key%3Ddpf43f3p2l4k3l03%26oauth_nonce%3Dkllo9940pd9333jh%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1191242096%26oauth_token%3Dnnch734d00sl2jdk%26oauth_version%3D1.0%26size%3Doriginal'
expected_oauth_signture = 'tR3+Ty81lMeYAr/Fid0kMTYa/WM='
http = 'GET'
url = 'http://photos.example.net/photos'
# Sort keys
params = {
'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'
}
params = urlencode(params)
base_string = signature_base_string(
http_method=http,
base_str_uri=url,
normalized_encoded_request_parameters=params
)
is_equal = base_string == expected_base_string
print(f'base string ok: {is_equal}')
consumer_secret = 'kd94hf93k423kf44'
consumer_key = 'pfkkdhi9sl3r4s00'
sign_key = f'{consumer_secret}&{consumer_key}'
base_string = base_string.encode('utf-8')
sign_key = sign_key.encode('utf-8')
# temp = hmac.new(base_string, sign_key, hashlib.sha1).hexdigest()
temp = hmac.new(sign_key, base_string, hashlib.sha1).hexdigest()
oauth_signature = b64encode(binascii.unhexlify(temp)) # bytes
is_equal = oauth_signature.decode() == expected_oauth_signture
print(f'oauth signature ok: {is_equal}')
print(oauth_signature)
test_compose_oauth1a_signature()
@realFranco
Copy link
Author

# Prints
base string ok: True
oauth signature ok: True
b'tR3+Ty81lMeYAr/Fid0kMTYa/WM='

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment