How to securely verify an HMAC in Python 2.7?

限于喜欢 提交于 2019-12-05 14:50:51

For anyone finding this from search, if using Django, then you can also use the constant_time_compare function in django.utils.crypto.

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

That this comes with the same caveat as hmac.compare_digest (and actually uses hmac.compare_digest if it exists):

Note: If a and b are of different lengths, or if an error occurs, a timing attack could theoretically reveal information about the types and lengths of a and b–but not their values.

I would suggest you just use the secure compare method available in 3.3.

This is an implementation that is very similar to the Python implementation:

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

Can't see how that would breach any licenses.

If you have access to Python 2.7.7, compare_digest() was recently backported to this version (as well as the more secure 3.x SSL module in 2.7.9).

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!