38 lines
990 B
Python
38 lines
990 B
Python
import json
|
|
import time
|
|
import hmac
|
|
import secrets
|
|
import hashlib
|
|
from typing import Dict, Any
|
|
|
|
def generate_signed_headers(app_id: str, app_secret: str, data: Dict[str, Any], method: str = "POST") -> Dict[str, str]:
|
|
timestamp = str(int(time.time() * 1000))
|
|
nonce = secrets.token_hex(16)
|
|
|
|
payload_str = json.dumps(data, ensure_ascii=False)
|
|
payload_bytes = payload_str.encode("utf-8")
|
|
actual_body_hash = hashlib.sha256(payload_bytes).hexdigest()
|
|
|
|
string_to_sign = "\n".join([
|
|
method.upper(),
|
|
app_id,
|
|
timestamp,
|
|
nonce,
|
|
actual_body_hash
|
|
])
|
|
|
|
signature = hmac.new(
|
|
app_secret.encode("utf-8"),
|
|
string_to_sign.encode("utf-8"),
|
|
hashlib.sha256
|
|
).hexdigest()
|
|
|
|
headers = {
|
|
"X-Ca-Appid": app_id,
|
|
"X-Ca-Timestamp": timestamp,
|
|
"X-Ca-Nonce": nonce,
|
|
"X-Ca-Signature": signature,
|
|
"Content-Type": "application/json; charset=utf-8"
|
|
}
|
|
|
|
return headers |