on master help sign in
[fix] secret_key can be bytes instead of a string (#1602)
ec88fb8rachmadani haryono
searx/utils.py+8−1
@@ -384,10 +384,17 @@ def load_module(filename, module_dir):
384
384
385
385
386def new_hmac(secret_key, url):
386def new_hmac(secret_key, url):
387+ try:
388+ secret_key_bytes = bytes(secret_key, 'utf-8')
389+ except TypeError as err:
390+ if isinstance(secret_key, bytes):
391+ secret_key_bytes = secret_key
392+ else:
393+ raise err
387 if sys.version_info[0] == 2:
394 if sys.version_info[0] == 2:
388 return hmac.new(bytes(secret_key), url, hashlib.sha256).hexdigest()
395 return hmac.new(bytes(secret_key), url, hashlib.sha256).hexdigest()
389 else:
396 else:
390− return hmac.new(bytes(secret_key, 'utf-8'), url, hashlib.sha256).hexdigest()
397+ return hmac.new(secret_key_bytes, url, hashlib.sha256).hexdigest()
391
398
392
399
393def to_string(obj):
400def to_string(obj):
tests/unit/test_utils.py+14
@@ -128,3 +128,17 @@ class TestUnicodeWriter(SearxTestCase):
128 rows = [1, 2, 3]
128 rows = [1, 2, 3]
129 self.unicode_writer.writerows(rows)
129 self.unicode_writer.writerows(rows)
130 self.assertEqual(self.unicode_writer.writerow.call_count, len(rows))
130 self.assertEqual(self.unicode_writer.writerow.call_count, len(rows))
131+
132+
133+class TestNewHmac(SearxTestCase):
134+
135+ def test_bytes(self):
136+ for secret_key in ['secret', b'secret', 1]:
137+ if secret_key == 1:
138+ with self.assertRaises(TypeError):
139+ utils.new_hmac(secret_key, b'http://example.com')
140+ continue
141+ res = utils.new_hmac(secret_key, b'http://example.com')
142+ self.assertEqual(
143+ res,
144+ '23e2baa2404012a5cc8e4a18b4aabf0dde4cb9b56f679ddc0fd6d7c24339d819')