如何在 Python 2.7 中安全地验证 HMAC



我正在使用Python 2.7,并使用hmac库创建HMAC。Python 3.3 包含一个compare_digest()函数,可以比较两个摘要并抵抗定时攻击,但这在 2.7 中不可用。普遍的建议是不要滚动我自己的加密货币,那么是否有任何成熟的 Python 库提供该功能?PyCrypto似乎没有。

对于从搜索中找到它的人,如果使用 Django,那么您也可以在 django.utils.crypto 中使用 constant_time_compare 函数。

>>> from django.utils.crypto import constant_time_compare
>>> constant_time_compare("foo", "bar")
False
>>> constant_time_compare("foo", "foo")
True

这与hmac.compare_digest具有相同的警告(如果存在,则实际使用hmac.compare_digest(:

注意:如果a和b的长度不同,或者发生错误,定时攻击理论上可以揭示有关a和b的类型和长度的信息,但不能显示它们的值。

我建议您只使用3.3中提供的安全比较方法。

这是一个与 Python 实现非常相似的实现:

def compare_digest(x, y):
    if not (isinstance(x, bytes) and isinstance(y, bytes)):
        raise TypeError("both inputs should be instances of bytes")
    if len(x) != len(y):
        return False
    result = 0
    for a, b in zip(x, y):
        result |= a ^ b
    return result == 0

看不出这将如何违反任何许可证。

如果你可以访问Python 2.7.7,compare_digest()最近被向后移植到这个版本(以及2.7.9中更安全的3.x SSL模块(。

https://www.python.org/dev/peps/pep-0466/

最新更新