Path: blob/master/bitget-python-sdk-api/bitget/utils.py
732 views
import base641import hmac2import time34from Crypto.Hash import SHA2565from Crypto.PublicKey import RSA6from Crypto.Signature import PKCS1_v1_5 as pk78from . import consts as c91011def sign(message, secret_key):12mac = hmac.new(bytes(secret_key, encoding='utf8'), bytes(message, encoding='utf-8'), digestmod='sha256')13d = mac.digest()14return str(base64.b64encode(d), 'utf8')1516def signByRSA(message, secret_key):17privatekey = RSA.importKey(secret_key)18h = SHA256.new(message.encode('utf-8'))19signer = pk.new(privatekey)20sign = signer.sign(h)21return str(base64.b64encode(sign), 'utf8')222324def pre_hash(timestamp, method, request_path, body = ""):25return str(timestamp) + str.upper(method) + request_path + body262728def get_header(api_key, sign, timestamp, passphrase):29header = dict()30header[c.CONTENT_TYPE] = c.APPLICATION_JSON31header[c.OK_ACCESS_KEY] = api_key32header[c.OK_ACCESS_SIGN] = sign33header[c.OK_ACCESS_TIMESTAMP] = str(timestamp)34header[c.OK_ACCESS_PASSPHRASE] = passphrase35header[c.LOCALE] = 'zh-CN'3637return header383940def parse_params_to_str(params):41params = [(key, val) for key, val in params.items()]42params.sort(key=lambda x: x[0])43# from urllib.parse import urlencode44# url = '?' +urlencode(params);45url = '?' +toQueryWithNoEncode(params);46if url == '?':47return ''48return url49# url = '?'50# for key, value in params.items():51# url = url + str(key) + '=' + str(value) + '&'52#53# return url[0:-1]5455def toQueryWithNoEncode(params):56url = ''57for key, value in params:58url = url + str(key) + '=' + str(value) + '&'59return url[0:-1]606162def get_timestamp():63return int(time.time() * 1000)646566def signature(timestamp, method, request_path, body, secret_key):67if str(body) == '{}' or str(body) == 'None':68body = ''69message = str(timestamp) + str.upper(method) + request_path + str(body)70mac = hmac.new(bytes(secret_key, encoding='utf8'), bytes(message, encoding='utf-8'), digestmod='sha256')71d = mac.digest()72return base64.b64encode(d)7374def check_none(value, msg=""):75if not value:76raise Exception(msg + " Invalid params!")7778