forked from imagekit-developer/imagekit-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcalculation.py
More file actions
39 lines (29 loc) · 1.06 KB
/
Copy pathcalculation.py
File metadata and controls
39 lines (29 loc) · 1.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import hashlib
import hmac
import uuid
from datetime import datetime as dt
from imagekitio.constants import ERRORS
DEFAULT_TIME_DIFF = 60 * 30
def hamming_distance(first: str, second: str) -> int:
"""Calculate Hamming Distance between to hex string
"""
try:
a = bin(int(first, 16))[2:].zfill(64)
b = bin(int(second, 16))[2:].zfill(64)
except TypeError:
raise TypeError(ERRORS.INVALID_PHASH_VALUE.value)
return len(list(filter(lambda x: ord(x[0]) ^ ord(x[1]), zip(a, b))))
def get_authenticated_params(token, expire, private_key):
default_expire = int(dt.now().strftime("%s")) + DEFAULT_TIME_DIFF
auth_params = {"token": token, "expire": expire, "signature": ""}
if not private_key:
return
signature = hmac.new(
key=private_key.encode(),
msg=(token + str(expire)).encode(),
digestmod=hashlib.sha1,
).hexdigest()
auth_params["token"] = token or str(uuid.uuid4())
auth_params["expire"] = expire or default_expire
auth_params["signature"] = signature
return auth_params