File size: 2,360 Bytes
e51f077
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import hmac
import hashlib
import base64
import requests
from datetime import datetime, timezone

class BearerTokenGenerator:
    def __init__(self, secret_key, secret_auth_prefix, path, base_url, api_version):
        self.secret_key = secret_key
        self.secret_auth_prefix = secret_auth_prefix
        self.path = path
        self.base_url = base_url
        self.api_version = api_version

    def generate_signature(self, to_sign):
        hmac_obj = hmac.new(self.secret_key, to_sign, hashlib.sha256)
        return base64.b64encode(hmac_obj.digest()).decode('utf-8')

    def get_bearer_token(self, body):
        # 获取当前UTC时间戳
        timestamp = datetime.now(timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ')
        prefix = f"POST:{self.path}:{timestamp}\n".encode('utf-8')

        # 生成签名
        signature = self.generate_signature(prefix + body)

        # 编码secretAuthPrefix
        encoded_secret_auth_prefix = base64.b64encode(self.secret_auth_prefix).decode('utf-8')

        # 构建Bearer Token
        bearer_token = f"Bearer {encoded_secret_auth_prefix}.{signature}"

        return bearer_token, timestamp

    def make_request(self, body):
        bearer_token, timestamp = self.get_bearer_token(body)
        headers = {
            "Date": timestamp,
            "Client-time-zone": "-04:00",
            "Authorization": bearer_token,
            "User-Agent": f"ChatOn_Android/{self.api_version}",
            "Accept-Language": "en-US",
            "X-Cl-Options": "hb",
            "Content-Type": "application/json; charset=UTF-8"
        }
        response = requests.post(self.base_url + self.path, headers=headers, data=body)
        return response.text

# 示例使用
if __name__ == "__main__":
    secret_key = bytes([14, 94, 79, 102, 38, 245, 11, 65, 100, 43, 115, 94, 15, 241, 14, 16, 66, 129, 248, 226, 98, 109, 235, 60, 62, 41, 78, 29, 72, 181, 47, 8])
    secret_auth_prefix = bytes([252, 137, 185, 155, 127, 94, 106, 81, 69, 242, 189, 184, 26, 228, 174, 239])
    path = "/chats/stream"
    base_url = "https://example.com/api"  # 替换为实际的BaseURL
    api_version = "1.0"

    body = '{"key": "value"}'.encode('utf-8')

    generator = BearerTokenGenerator(secret_key, secret_auth_prefix, path, base_url, api_version)
    response = generator.make_request(body)
    print(response)