1. hashlib密码散列

hashlib模块定义了一个API来访问不同的密码散列算法。要使用一个特定的散列算法，可以用适当的构造器函数或new()来创建一个散列对象。不论使用哪个具体的算法，这些对象都使用相同的API。

1.1 散列算法

md5

sha1

sha224

sha256

sha384

sha512

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, RIPEMD160, SHA, SHA1, SHA224, SHA256, SHA384, SHA512, blake2b, blake2s, dsaEncryption, dsaWithSHA, ecdsa-with-SHA1, md4, md5, ripemd160, sha, sha1, sha224, sha256, sha384, sha3_224, sha3_256, sha3_384, sha3_512, sha512, shake_128, shake_256, whirlpool

1.2 MD5示例

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.'''

h = hashlib.md5()
h.update(lorem.encode('utf-8'))
print(h.hexdigest())

1.3 SHA1示例

SHA1摘要也用同样的方式计算。

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.'''

h = hashlib.sha1()
h.update(lorem.encode('utf-8'))
print(h.hexdigest())

1.4 增量更新

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.'''

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))

posted @ 2020-03-28 17:13  SmallGrayCode  阅读(350)  评论(0编辑  收藏  举报