summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorWouter Bolsterlee <wouter@intelworks.com>2015-01-05 20:15:06 +0100
committerWouter Bolsterlee <wouter@intelworks.com>2015-01-05 20:16:23 +0100
commit0338a46d057230a2eef0a894c09d3297b0df9d93 (patch)
tree7d76490cf8ecbb74f6fdb0fa1f83200fb7087307
parent1a38e31b4d4b2a266a2ea544ec10fe269c880b6f (diff)
downloadpyjwt-0338a46d057230a2eef0a894c09d3297b0df9d93.tar.gz
Use constant time string comparison routine from hmac module
...and only use the current implementation as a fallback. Fixes #63.
-rw-r--r--jwt/__init__.py44
1 files changed, 24 insertions, 20 deletions
diff --git a/jwt/__init__.py b/jwt/__init__.py
index ad58188..85b4058 100644
--- a/jwt/__init__.py
+++ b/jwt/__init__.py
@@ -212,26 +212,30 @@ except ImportError:
pass
-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.
- """
- if len(val1) != len(val2):
- return False
-
- result = 0
-
- if sys.version_info >= (3, 0, 0):
- # Bytes are numbers
- for x, y in zip(val1, val2):
- result |= x ^ y
- else:
- for x, y in zip(val1, val2):
- result |= ord(x) ^ ord(y)
-
- return result == 0
+try:
+ constant_time_compare = hmac.compare_digest
+except AttributeError:
+ # Fallback for Python < 2.7.7 and Python < 3.3
+ 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.
+ """
+ if len(val1) != len(val2):
+ return False
+
+ result = 0
+
+ if sys.version_info >= (3, 0, 0):
+ # Bytes are numbers
+ for x, y in zip(val1, val2):
+ result |= x ^ y
+ else:
+ for x, y in zip(val1, val2):
+ result |= ord(x) ^ ord(y)
+
+ return result == 0
def base64url_decode(input):