4

I need to compute a hash of an integer using python 3. Is there a cleaner and more efficient solution than the following?

>>> import hashlib >>> N = 123 >>> hashlib.md5(str(N).encode("ascii")).hexdigest() '202cb962ac59075b964b07152d234b70' 

It seems weird to have to convert to a unicode string, then decode it to a byte array.

2 Answers 2

3

A cryptographic hash such as MD5 can only be applied to bytes. There are more efficient ways of encoding a number as bytes, but you still need to follow the contract.

>>> hashlib.md5(int(-123).to_bytes(8, 'big', signed=True)).hexdigest() 'fc1063e1bcb35f0d52cdceae4626c39b' 
Sign up to request clarification or add additional context in comments.

3 Comments

Great, thanks Ignacio. I didn't know you could call methods on ints. Do you know how to do this in python 2 by any chance?
For Python 2.x you need to use struct to pack it into a bytestring.
Yikes. One more reason to prefer python 3, then. Thanks again.
1

Ignacio's answer is perfect, but in case you need the code to work with both python 2 and python 3, and if you have NumPy installed, then this works great:

>>> import numpy as np >>> import hashlib.md5 >>> N = 123 >>> hashlib.md5(np.int64(N)).hexdigest() 'f18b8dbefe02a0efce281deb55a209cd' 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.