diff --git a/Lib/hmac.py b/Lib/hmac.py --- a/Lib/hmac.py +++ b/Lib/hmac.py @@ -20,15 +20,22 @@ (isinstance(a, bytes) and isinstance(b, bytes))): raise TypeError("inputs must be strings or bytes") - if len(a) != len(b): - return False + # keep constant time even when strings don't have equal length + # the second 'if' is used instead of an 'else' block to keep + # the amount of CPU instructions constant. + len_eq = len(a) == len(b) + if len_eq: + result = 0 + left = a + if not len_eq: + result = 1 + left = b - result = 0 - if isinstance(a, bytes): - for x, y in zip(a, b): + if isinstance(left, bytes): + for x, y in zip(left, b): result |= x ^ y else: - for x, y in zip(a, b): + for x, y in zip(left, b): result |= ord(x) ^ ord(y) return result == 0