| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990 |
- """
- 签名层单元测试
- ==============
- 验证 key_sort / hmac_sha1_hex / sign_params 与前端 JS 一致。
- 不需要联网,不需要 996 账号密码。
- """
- import sys
- import unittest
- from pathlib import Path
- # 让 tests 能 import 包
- sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
- from chuanshi_login.crypto import hmac_sha1_hex, key_sort, sign_params
- class TestKeySort(unittest.TestCase):
- def test_basic_alpha_sort(self):
- # 按字母序升序
- params = {"b": "2", "a": "1", "c": "3"}
- self.assertEqual(key_sort(params), "a=1&b=2&c=3")
- def test_matches_protocolInit(self):
- """复现前端 protocolInit 调 appParam 时的签名输入"""
- params = {
- "appid": 155342,
- "game_id": 214256,
- "vType": "csvKey",
- }
- result = key_sort(params)
- self.assertEqual(result, "appid=155342&game_id=214256&vType=csvKey")
- def test_login_payload(self):
- """复现前端 toLogin 调 v5w/login 时的参数顺序(不计算 sign)"""
- params = {
- "username": "abc",
- "password": "xxx",
- "game_id": 1,
- "vType": "csvKey",
- "appid": 1,
- "promote_id": 0,
- "_device_info": "...",
- }
- result = key_sort(params)
- # 验证包含每个字段
- for k in params:
- self.assertIn(f"{k}=", result)
- def test_empty_value(self):
- # None 视为空字符串
- self.assertEqual(key_sort({"a": None, "b": "x"}), "a=&b=x")
- class TestHmacSha1(unittest.TestCase):
- KEY = "k1ebbkxlojjdbnffnp3w2ykk3p625xnn"
- def test_known_vector(self):
- # 与 verify_poc.py 跑出来的结果对照
- msg = "appid=155342&game_id=214256&vType=csvKey"
- sig = hmac_sha1_hex(msg, self.KEY)
- self.assertEqual(sig, "1470dbc89058c62ac4c39bd30c5097b140017528")
- def test_stable(self):
- # 同一输入两次结果一致
- msg = "a=1&b=2"
- self.assertEqual(hmac_sha1_hex(msg, self.KEY), hmac_sha1_hex(msg, self.KEY))
- class TestSignParams(unittest.TestCase):
- KEY = "k1ebbkxlojjdbnffnp3w2ykk3p625xnn"
- def test_adds_sign(self):
- params = {"appid": 155342, "game_id": 214256, "vType": "csvKey"}
- signed = sign_params(params, self.KEY)
- self.assertIn("sign", signed)
- # 不修改入参
- self.assertNotIn("sign", params)
- def test_sign_known_value(self):
- params = {"appid": 155342, "game_id": 214256, "vType": "csvKey"}
- signed = sign_params(params, self.KEY)
- # sign = URL-encoded hex of hmac_sha1_hex(sorted_str, key)
- # 与 verify_poc.py 一致
- self.assertEqual(signed["sign"], "1470dbc89058c62ac4c39bd30c5097b140017528")
- if __name__ == "__main__":
- unittest.main(verbosity=2)
|