#Python Signature Generator
#signature_generator.py
import hashlib
import hmac
import json
import urllib
class Signature:
def __init__(self, hash: str, salt: str):
self.hash = hash
self.salt = salt
class SignatureGenerator:
def generate(self, url: str, params: dict, secret: str, salt: str = '') -> Signature:
path = urllib.parse.urlparse(url).path
to_sign = path + self.get_values(params) + salt
hash = hmac.new(secret.encode('utf-8'), to_sign.encode('utf-8'), hashlib.sha256).hexdigest()
return Signature(hash, salt)
def get_values(self, obj: dict) -> str:
values = []
obj = {k: obj[k] for k in sorted(obj.keys())}
for key in obj:
value = obj[key]
if isinstance(value, list) or isinstance(value, dict):
values.extend(self.get_values(value))
continue
if isinstance(value, bool):
values.append('1' if value else '0')
continue
values.append(str(value) if value else '')
return ''.join(values)