diff options
author | Charles-François Natali <neologix@free.fr> | 2012-05-13 19:53:07 +0200 |
---|---|---|
committer | Charles-François Natali <neologix@free.fr> | 2012-05-13 19:53:07 +0200 |
commit | 7feb9f42258ff72ce1d3628c5ccc261c2ca238b9 (patch) | |
tree | 3ac35288be0b37833dfe58cc5829a7c0cf9b3f3f /Lib/hmac.py | |
parent | d200bf534b6d97ee607e1071d0cb2d93e4506268 (diff) | |
download | cpython-git-7feb9f42258ff72ce1d3628c5ccc261c2ca238b9.tar.gz |
Issue #14532: Add a secure_compare() helper to the hmac module, to mitigate
timing attacks. Patch by Jon Oberheide.
Diffstat (limited to 'Lib/hmac.py')
-rw-r--r-- | Lib/hmac.py | 21 |
1 files changed, 21 insertions, 0 deletions
diff --git a/Lib/hmac.py b/Lib/hmac.py index 956fc65d2c..13ffdbe14b 100644 --- a/Lib/hmac.py +++ b/Lib/hmac.py @@ -13,6 +13,27 @@ trans_36 = bytes((x ^ 0x36) for x in range(256)) 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. |