Search code examples
pythonpython-3.xpython-2.xhmachashlib

Why is this hmac digest different on Python 2.7 and Python 3.7?


I'm trying to move a project from Python 2.7 to Python 3.7 and run into an issue with an hmac digest. Running the following code produces 2 different results

import hmac, hashlib
print(hmac.new(bytes([]), bytes([]), hashlib.sha1).hexdigest())

On Python 2.7: 1bd590e48bea8f0c8cc70602bc55d317c3de7c52

On Python 3.7: fbdb1d1b18aa6c08324b7d64b71fb76370690e1d

Why are these two results different?


Solution

  • In Python 3.7, bytes() and bytes([]) are both interpreted as b''.

    In Python 2.7, bytes() is interpreted as '' which is roughly equivalent to b'' in Python 3.7.

    However, Python 2.7 interprets bytes([]) as '[]'.

    That is the source of the difference. If you use bytes() or b'' instead of bytes([]), you should get the same result in both Python 2.7 and Python 3.7.