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.
In [1]:
import hashlib
print('Guaranteed:\n{}\n'.format(
', '.join(sorted(hashlib.algorithms_guaranteed))))
print('Available:\n{}'.format(
', '.join(sorted(hashlib.algorithms_available))))
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.'''
In [4]:
import hashlib
h = hashlib.md5()
h.update(lorem.encode('utf8'))
print(h.hexdigest())
In [5]:
import hashlib
h = hashlib.sha1()
h.update(lorem.encode('utf-8'))
print(h.hexdigest())
In [8]:
import hashlib
h = hashlib.new('sha256')
h.update(lorem.encode('utf-8'))
print(h.hexdigest())
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))