Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to securely verify an HMAC in Python 2.7?

I'm using Python 2.7 and am creating an HMAC using the hmac library. Python 3.3 includes a compare_digest() function that will compare two digests and resist timing attacks, but that's not available in 2.7. Prevailing advice is not to roll my own crypto, so are there any mature Python libraries that provide that functionality? PyCrypto does not appear to.

like image 233
Andrew Buss Avatar asked Mar 23 '23 20:03

Andrew Buss


1 Answers

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.

like image 140
zelanix Avatar answered Mar 27 '23 16:03

zelanix