Mercurial > cpython-lru_cache-weakref
diff Lib/hmac.py @ 76906:ddcc8ee680d7
Issue #14532: Add a secure_compare() helper to the hmac module, to mitigate
timing attacks. Patch by Jon Oberheide.
| author | Charles-François Natali <neologix@free.fr> |
|---|---|
| date | Sun, 13 May 2012 19:53:07 +0200 |
| parents | 8e57b5d8f58f |
| children | f36af3766a20 |
line wrap: on
line diff
--- a/Lib/hmac.py Sun May 13 13:45:09 2012 -0400 +++ b/Lib/hmac.py Sun May 13 19:53:07 2012 +0200 @@ -13,6 +13,27 @@ digest_size = None +def secure_compare(a, b): + """Returns the equivalent of 'a == b', but using a time-independent + comparison method to prevent timing attacks.""" + if not ((isinstance(a, str) and isinstance(b, str)) or + (isinstance(a, bytes) and isinstance(b, bytes))): + raise TypeError("inputs must be strings or bytes") + + if len(a) != len(b): + return False + + result = 0 + if isinstance(a, bytes): + for x, y in zip(a, b): + result |= x ^ y + else: + for x, y in zip(a, b): + result |= ord(x) ^ ord(y) + + return result == 0 + + class HMAC: """RFC 2104 HMAC class. Also complies with RFC 4231.
