hash

Befunny 于 2018-06-10 发布

hashlib提供常见的hash算法,如md5、sha1、sha256等。

这些算法先前叫做message digest,现在叫做secure hash

Usage

Construct

两种方法来构造hash object,一个为跟算法同名的构造函数,另一个是通用的构造函数。

import hashlib
m = hashlib.md5()
m.update(b'hello world')
result = m.digest()

update the hash object with the bytes

这里需要注意的是update方法的参数为bytes类型

连续多次调用实例的update方法,与处理结合的结果等效,如下列两个代码块等价。

m.update(b'hello')
m.update(b' world')
m.digest()

m.update(b'hello world')
m.digest()

计算hash

hash.digest()返回调用此方法之前的所有update中的参数的hash结果,类型为bytes,大小为hash.digest_size

hash.hexdigest()返回string格式结果。

属性

属性 说明
hashlib.alogrithms_guaranteed 所有平台上都被此模块支持的算法集合
hash.digest_size hash结果字节大小
hash.block_size hash算法的内部块字节大小
hash.name 算法名称,一般为小写