From b45c0ff831560016e84cfa4528a44758702f235f Mon Sep 17 00:00:00 2001 From: William Gibb Date: Mon, 2 Nov 2015 11:29:57 -0500 Subject: [PATCH] Update utils.py to define two different constant time comparisons; one which is appropriate for use w/ Python2 and one which is appropriate for use with Python3. Unit tests were previously failing on python3, and no longer fail with this update. --- jws/utils.py | 49 +++++++++++++++++++++++++++++++++---------------- 1 file changed, 33 insertions(+), 16 deletions(-) diff --git a/jws/utils.py b/jws/utils.py index 091adf4..a113e83 100644 --- a/jws/utils.py +++ b/jws/utils.py @@ -31,20 +31,37 @@ def encode(a): return to_base64(to_json(a)) def decode(a): return from_json(from_base64(a)) #Taken from Django Source Code +if binary_type == str: + def constant_time_compare(val1, val2): + """ + Returns True if the two strings are equal, False otherwise. -def constant_time_compare(val1, val2): - """ - Returns True if the two strings are equal, False otherwise. - - The time taken is independent of the number of characters that match. - - For the sake of simplicity, this function executes in constant time only - when the two strings have the same length. It short-circuits when they - have different lengths. - """ - if len(val1) != len(val2): - return False - result = 0 - for x, y in zip(val1, val2): - result |= ord(x) ^ ord(y) - return result == 0 + The time taken is independent of the number of characters that match. + + For the sake of simplicity, this function executes in constant time only + when the two strings have the same length. It short-circuits when they + have different lengths. + """ + if len(val1) != len(val2): + return False + result = 0 + for x, y in zip(val1, val2): + result |= ord(x) ^ ord(y) + return result == 0 +else: + def constant_time_compare(val1, val2): + """ + Returns True if the two strings are equal, False otherwise. + + The time taken is independent of the number of characters that match. + + For the sake of simplicity, this function executes in constant time only + when the two strings have the same length. It short-circuits when they + have different lengths. + """ + if len(val1) != len(val2): + return False + result = 0 + for x, y in zip(val1, val2): + result |= x ^ y + return result == 0 \ No newline at end of file