How to safely test HMAC in Python 2.7?

I am using Python 2.7 and creating HMAC using the hmac library. Python 3.3 includes the compare_digest() function, which will compare two digests and resist synchronization attacks, but this is not available in 2.7. The overwhelming advice is not to overturn my own cryptoal, so are there any mature Python libraries that provide this functionality? PyCrypto is not displayed.

+4
source share
3 answers

For those who find this from a search using Django, 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 

As for the same caution as hmac.compare_digest (and actually uses hmac.compare_digest if one exists):

Note. . If a and b have different lengths or an error occurs, then a temporary attack can theoretically reveal information about the types and lengths of a and b, but not their values.

+3
source

I would suggest you use the secure comparison method available in version 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 

It is impossible to see how this violates any licenses.

+3
source

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

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

+1
source

Source: https://habr.com/ru/post/1496380/


All Articles