14.2. hmac — 基于密钥的消息验证

2.2 新版功能.

源代码: Lib/hmac.py


此模块实现了 HMAC 算法,算法的描述参见 RFC 2104

hmac.new(key[, msg[, digestmod]])

Return a new hmac object. If msg is present, the method call update(msg) is made. digestmod is the digest constructor or module for the HMAC object to use. It defaults to the hashlib.md5 constructor.

HMAC 对象具有下列方法:

HMAC.update(msg)

Update the hmac object with the string msg. Repeated calls are equivalent to a single call with the concatenation of all the arguments: m.update(a); m.update(b) is equivalent to m.update(a + b).

HMAC.digest()

Return the digest of the strings passed to the update() method so far. This string will be the same length as the digest_size of the digest given to the constructor. It may contain non-ASCII characters, including NUL bytes.

警告

在验证例程运行期间将 digest() 的输出与外部提供的摘要进行比较时,建议使用 compare_digest() 函数而不是 == 运算符以减少定时攻击防御力的不足。

HMAC.hexdigest()

类似于 digest() 但摘要会以两倍长度字符串的形式返回,其中仅包含十六进制数码。 这可以被用于在电子邮件或其他非二进制环境中安全地交换数据值。

警告

在验证例程运行期间将 hexdigest() 的输出与外部提供的摘要进行比较时,建议使用 compare_digest() 函数而不是 == 运算符以减少定时攻击防御力的不足。

HMAC.copy()

返回 hmac 对象的副本(“克隆)。 这可被用来高效地计算共享相同初始子串的数据的摘要。

这个模块还提供了下列辅助函数:

hmac.compare_digest(a, b)

Return a == b. This function uses an approach designed to prevent timing analysis by avoiding content-based short circuiting behaviour, making it appropriate for cryptography. a and b must both be of the same type: either unicode or a bytes-like object.

注解

如果 ab 具有不同的长度,或者如果发生了错误,定时攻击在理论上可以获取有关 ab 的类型和长度信息 — 但不能获取它们的值。

2.7.7 新版功能.

参见

模块 hashlib

提供安全哈希函数的 Python 模块。