The hashlib module defines an API for accessing different cryptographic hashing algorithms. To work with a specific hash algorithm, use the appropriate constructor function or new() to create a hash object. From there, the objects use the same API, no matter what algorithm is being used.

Hash Algorithms


In [1]:
import hashlib


print('Guaranteed:\n{}\n'.format(
    ', '.join(sorted(hashlib.algorithms_guaranteed))))
print('Available:\n{}'.format(
    ', '.join(sorted(hashlib.algorithms_available))))


Guaranteed:
blake2b, blake2s, md5, sha1, sha224, sha256, sha384, sha3_224, sha3_256, sha3_384, sha3_512, sha512, shake_128, shake_256

Available:
DSA, DSA-SHA, MD4, MD5, MDC2, RIPEMD160, SHA, SHA1, SHA224, SHA256, SHA384, SHA512, blake2b, blake2s, dsaEncryption, dsaWithSHA, ecdsa-with-SHA1, md4, md5, mdc2, ripemd160, sha, sha1, sha224, sha256, sha384, sha3_224, sha3_256, sha3_384, sha3_512, sha512, shake_128, shake_256, whirlpool

In [2]:
import hashlib

lorem = '''Lorem ipsum dolor sit amet, consectetur adipisicing
elit, sed do eiusmod tempor incididunt ut labore et dolore magna
aliqua. Ut enim ad minim veniam, quis nostrud exercitation
ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis
aute irure dolor in reprehenderit in voluptate velit esse cillum
dolore eu fugiat nulla pariatur. Excepteur sint occaecat
cupidatat non proident, sunt in culpa qui officia deserunt
mollit anim id est laborum.'''

MD5 Example


In [4]:
import hashlib
h = hashlib.md5()
h.update(lorem.encode('utf8'))
print(h.hexdigest())


3f2fd2c9e25d60fb0fa5d593b802b7a8

Sha1 Example


In [5]:
import hashlib
h = hashlib.sha1()
h.update(lorem.encode('utf-8'))
print(h.hexdigest())


ea360b288b3dd178fe2625f55b2959bf1dba6eef

Change by Name


In [8]:
import hashlib
h = hashlib.new('sha256')
h.update(lorem.encode('utf-8'))
print(h.hexdigest())


3c887cc71c67949df29568119cc646f46b9cd2c2b39d456065646bc2fc09ffd8

Incresmental Updates


In [9]:
import hashlib
h = hashlib.md5()
h.update(lorem.encode('utf-8'))
all_at_once = h.hexdigest()


def chunkize(size, text):
    "Return parts of the text in size-based increments."
    start = 0
    while start < len(text):
        chunk = text[start:start + size]
        yield chunk
        start += size
    return

h = hashlib.md5()
for chunk in chunkize(64, lorem.encode('utf-8')):
    h.update(chunk)
line_by_line = h.hexdigest()

print('All at once :', all_at_once)
print('Line by line:', line_by_line)
print('Same        :', (all_at_once == line_by_line))


All at once : 3f2fd2c9e25d60fb0fa5d593b802b7a8
Line by line: 3f2fd2c9e25d60fb0fa5d593b802b7a8
Same        : True