Inconsistency in HMAC signature generation in Python 3? -
running create_api_signature()
method in python terminal return same value, while return different values when run in test.
import hashlib import hmac import json import unittest def create_api_signature(_method, _url, _body, _timestamp, _secret_key): unicode_signature = _method.upper() + _url + json.dumps(_body) + str(_timestamp) s = hmac.new(_secret_key.encode(), unicode_signature.encode(), hashlib.sha256).hexdigest() return s class mytestcase(unittest.testcase): def test_create_signature(self): method = 'post' url = 'https://api.alpha.example.com/v1/tiers' body = { "mail": "test@gmail.com", "mot_de_passe": "mycomplexpassword", } timestamp = 1433948791 secret_key = 'secret_key' signature = create_api_signature(method, url, body, timestamp, secret_key) expected_signature = '136b629ac9744258cf558c2d541d563cc3ce647d91ead707ae4d42d49ade50c7' self.assertequal(expected_signature, signature) if __name__ == '__main__': unittest.main()
error
failure expected :'136b629ac9744258cf558c2d541d563cc3ce647d91ead707ae4d42d49ade50c7' actual :'88a138592ea7eae50040655387a878d15fd4ab4ade5d7d769a36bf9300cb3f9e' <click see difference> traceback (most recent call last): file "/home/elopez/projects/portal/tests/test_services.py", line 98, in test_create_signature self.assertequal(expected_signature, signature) assertionerror: '136b629ac9744258cf558c2d541d563cc3ce647d91ead707ae4d42d49ade50c7' != '88a138592ea7eae50040655387a878d15fd4ab4ade5d7d769a36bf9300cb3f9e' - 136b629ac9744258cf558c2d541d563cc3ce647d91ead707ae4d42d49ade50c7 + 88a138592ea7eae50040655387a878d15fd4ab4ade5d7d769a36bf9300cb3f9e
i went #python
's irc , following answer cdunklau
cdunklau: run few times , you'll see why
pythonhashseed=random python3.2 -c "import json; print(json.dumps({'mail': 'value', 'mot_de_passe': 'othervalue'}))"
cdunklau: you're depending on order of dict
mutability
$ in {1..20}; pythonhashseed=random python3.4 -c "import json; print(json.dumps({'mail': 'value', 'mot_de_passe': 'othervalue'}))"; done
give following result (notice json data not in same order):
{"mail": "value", "mot_de_passe": "othervalue"} {"mot_de_passe": "othervalue", "mail": "value"} {"mail": "value", "mot_de_passe": "othervalue"} {"mot_de_passe": "othervalue", "mail": "value"} {"mail": "value", "mot_de_passe": "othervalue"} {"mot_de_passe": "othervalue", "mail": "value"} {"mot_de_passe": "othervalue", "mail": "value"} …
solution
i changed from:
body = { "mail": "test@gmail.com", "mot_de_passe": "mycomplexpassword", }
to serialized dict binary string:
body = b'{"mail": "test@gmail.com", "mot_de_passe": "mycomplexpassword"}'
Comments
Post a Comment