Skip to content

Commit 73007d6

Browse files
author
Michael Davis
authored
Merge pull request #35 from mpdavis/hmac-timing
fix: Use constant time comparison for HMAC
2 parents 8f0ee80 + 89b4635 commit 73007d6

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed

jose/jwk.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
from jose.constants import ALGORITHMS
2020
from jose.exceptions import JWKError
2121
from jose.utils import base64url_decode
22+
from jose.utils import constant_time_string_compare
2223

2324
# PyCryptodome's RSA module doesn't have PyCrypto's _RSAobj class
2425
# Instead it has a class named RsaKey, which serves the same purpose.
@@ -159,7 +160,7 @@ def sign(self, msg):
159160
return hmac.new(self.prepared_key, msg, self.hash_alg).digest()
160161

161162
def verify(self, msg, sig):
162-
return sig == self.sign(msg)
163+
return constant_time_string_compare(sig, self.sign(msg))
163164

164165

165166
class RSAKey(Key):

jose/utils.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11

22
import base64
3+
import hmac
34

45

56
def calculate_at_hash(access_token, hash_alg):
@@ -58,3 +59,27 @@ def timedelta_total_seconds(delta):
5859
delta (timedelta): A timedelta to convert to seconds.
5960
"""
6061
return delta.days * 24 * 60 * 60 + delta.seconds
62+
63+
64+
def constant_time_string_compare(a, b):
65+
"""Helper for comparing string in constant time, independent
66+
of the python version being used.
67+
68+
Args:
69+
a (str): A string to compare
70+
b (str): A string to compare
71+
"""
72+
73+
try:
74+
return hmac.compare_digest(a, b)
75+
except AttributeError:
76+
77+
if len(a) != len(b):
78+
return False
79+
80+
result = 0
81+
82+
for x, y in zip(a, b):
83+
result |= ord(x) ^ ord(y)
84+
85+
return result == 0

0 commit comments

Comments
 (0)