import hashlib
import json
import base64
import time
from collections import OrderedDict
import random
import string
def generate_random_string(length):
letters_and_digits = string.ascii_letters + string.digits
return ''.join(random.choice(letters_and_digits) for i in range(length))
def generate_signature(timestamp, nonce, secret_id, secret_key):
# 按照字典顺序拼接字符串
print("timestamp:", timestamp)
print('nonce:', nonce)
print("secret_id:", secret_id)
print("secret_key:", secret_key)
params = OrderedDict([
("timeStamp", timestamp),
("nonce", nonce),
("secretId", secret_id),
("secretKey", secret_key)
])
signature_params = sorted(params.items())
sorted_params = "&".join([f"{k}={v}" for k, v in signature_params])
print('signature_str', sorted_params)
# 使用SHA1算法生成签名
sha1 = hashlib.sha1(sorted_params.encode('utf-8'))
signature = sha1.hexdigest()
return signature
def generate_authorization_header(timestamp, nonce, secret_id, secret_key):
# 生成签名
signature = generate_signature(timestamp, nonce, secret_id, secret_key)
# 构建JSON字符串
data = {"nonce": nonce,
"secretId": secret_id,
"signature": signature,
"timeStamp": timestamp
}
json_str = json.dumps(data, separators=(',', ':'))
print('json_str:', json_str)
# 对JSON字符串进行Base64编码
base64_str = base64.b64encode(json_str.encode('utf-8')).decode('utf-8')
# 构建Authorization头部
authorization_header = f"{base64_str}"
print('authorization_header:', authorization_header)
return authorization_header
# 示例使用
if __name__ == "__main__":
timestampStr = str(int(round(time.time() * 1000)))
timestamp = timestampStr
nonce = generate_random_string(4)
secret_id = "aakakkuk"
secret_key = "47cc736d8cf4525457324857255678"
authorization_header = generate_authorization_header(timestamp, nonce, secret_id, secret_key)
python使用SHA1加密(时间戳,随机字符串,调用方秘钥ID,调用方秘钥KEY)生成签名,将签名和时间戳,随机字符串,调用方秘钥ID再次进行Base64加密
最新推荐文章于 2024-08-26 08:54:09 发布