summaryrefslogtreecommitdiff
path: root/jwt/utils.py
diff options
context:
space:
mode:
authorMark Adams <mark@markadams.me>2015-01-06 08:15:11 -0600
committerMark Adams <mark@markadams.me>2015-01-18 10:28:01 -0600
commit9b0f0f13d9c2f74d36d0c4304a024fa7652392be (patch)
treefa42844f640caee470c9d4b09747a8878ef1c48d /jwt/utils.py
parent1da2d4a52d55d64f77d7c6d6b52cdba555dc0e0b (diff)
downloadpyjwt-9b0f0f13d9c2f74d36d0c4304a024fa7652392be.tar.gz
Created utils.py to hold functions like constant_time_compare and base64-encoding
Diffstat (limited to 'jwt/utils.py')
-rw-r--r--jwt/utils.py39
1 files changed, 39 insertions, 0 deletions
diff --git a/jwt/utils.py b/jwt/utils.py
new file mode 100644
index 0000000..16000b5
--- /dev/null
+++ b/jwt/utils.py
@@ -0,0 +1,39 @@
+import base64
+import hmac
+
+def base64url_decode(input):
+ rem = len(input) % 4
+
+ if rem > 0:
+ input += b'=' * (4 - rem)
+
+ return base64.urlsafe_b64decode(input)
+
+
+def base64url_encode(input):
+ return base64.urlsafe_b64encode(input).replace(b'=', b'')
+
+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