Python Language Calculating a Message Digest


The hashlib module allows creating message digest generators via the new method. These generators will turn an arbitrary string into a fixed-length digest:

import hashlib

h ='sha256')
h.update(b'Nobody expects the Spanish Inquisition.')
# ==> b'.\xdf\xda\xdaVR[\x12\x90\xff\x16\xfb\x17D\xcf\xb4\x82\xdd)\x14\xff\xbc\xb6Iy\x0c\x0eX\x9eF-='

Note that you can call update an arbitrary number of times before calling digest which is useful to hash a large file chunk by chunk. You can also get the digest in hexadecimal format by using hexdigest:

# ==> '2edfdada56525b1290ff16fb1744cfb482dd2914ffbcb649790c0e589e462d3d'