hashlib — 安全哈希和消息摘要

源代码: Lib/hashlib.py


This module implements a common interface to many different secure hash and message digest algorithms. Included are the FIPS secure hash algorithms SHA1, SHA224, SHA256, SHA384, SHA512, (defined in the FIPS 180-4 standard ), the SHA-3 series (defined in the FIPS 202 standard ) as well as RSA’s MD5 algorithm (defined in internet RFC 1321 )。术语 "安全哈希" 和 "消息摘要" 可互换。旧算法称为消息摘要。现代术语是安全哈希。

注意

若想要 adler32 (或 crc32) 哈希函数,可找到它们在 zlib 模块。

哈希算法

有一命名构造函数方法对于每种类型的 hash 。全部返回具有相同简单接口的哈希对象。例如:使用 sha256() 能创建 SHA-256 哈希对象。现在可以喂这种对象采用 像字节对象 (通常 bytes ) 使用 update 方法。在任何时候都可以向它请求 digest 为喂给它的串联数据,到目前为止是使用 digest() or hexdigest() 方法。

To allow multithreading, the Python GIL is released while computing a hash supplied more than 2047 bytes of data at once in its constructor or .update 方法。

此模块中始终存在的哈希算法构造函数包括 sha1() , sha224() , sha256() , sha384() , sha512() , sha3_224() , sha3_256() , sha3_384() , sha3_512() , shake_128() , shake_256() , blake2b() ,和 blake2s() . md5() is normally available as well, though it may be missing or blocked if you are using a rare “FIPS compliant” build of Python. These correspond to algorithms_guaranteed .

Additional algorithms may also be available if your Python distribution’s hashlib was linked against a build of OpenSSL that provides others. Others are not guaranteed available on all installations and will only be accessible by name via new() 。见 algorithms_available .

警告

Some algorithms have known hash collision weaknesses (including MD5 and SHA1). Refer to Attacks on cryptographic hash algorithms hashlib-seealso section at the end of this document.

Added in version 3.6: SHA3 (Keccak) 和 SHAKE 构造函数 sha3_224() , sha3_256() , sha3_384() , sha3_512() , shake_128() , shake_256() 被添加。 blake2b() and blake2s() 被添加。

3.9 版改变: 所有 hashlib 构造函数接受仅关键词自变量 usedforsecurity 采用默认值 True 。False 值允许在限定环境下使用不安全且阻塞的哈希算法。 False 指示在安全上下文中不使用哈希算法 (如:作为非加密单向压缩函数)。

3.9 版改变: Hashlib now uses SHA3 and SHAKE from OpenSSL if it provides it.

3.12 版改变: For any of the MD5, SHA1, SHA2, or SHA3 algorithms that the linked OpenSSL does not provide we fall back to a verified implementation from the HACL* project .

用法

To obtain the digest of the byte string b"Nobody inspects the spammish repetition" :

>>> import hashlib
>>> m = hashlib.sha256()
>>> m.update(b"Nobody inspects")
>>> m.update(b" the spammish repetition")
>>> m.digest()
b'\x03\x1e\xdd}Ae\x15\x93\xc5\xfe\\\x00o\xa5u+7\xfd\xdf\xf7\xbcN\x84:\xa6\xaf\x0c\x95\x0fK\x94\x06'
>>> m.hexdigest()
'031edd7d41651593c5fe5c006fa5752b37fddff7bc4e843aa6af0c950f4b9406'