get_kw_sign.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. # -*- coding: utf-8 -*-
  2. # Author : Charley
  3. # Python : 3.8.10
  4. # Date : 2025/4/15 10:29
  5. import hashlib
  6. import json
  7. import random
  8. import time
  9. def return_new_url(url_):
  10. # 去掉查询参数部分(? 后面的内容)
  11. path_without_query = url_.split("?")[0]
  12. # 按 "/" 分割路径
  13. path_parts = path_without_query.split("/")
  14. # 返回最后一部分
  15. return path_parts[-1]
  16. def generate_random_string():
  17. # 使用 random.random() 生成随机数并转换为 36 进制字符串,截取最后 10 个字符
  18. part1 = ''.join(random.choices('0123456789abcdefghijklmnopqrstuvwxyz', k=10))
  19. part2 = ''.join(random.choices('0123456789abcdefghijklmnopqrstuvwxyz', k=10))
  20. return part1 + part2
  21. #
  22. def sort_asc(t: dict):
  23. """
  24. 定义一个函数 sort_asc,用于对字典 t 的键进行排序,并返回一个新的字典 o
  25. :param t: dict
  26. :return: sorted_dict
  27. """
  28. # 按字母顺序对字典的键进行排序
  29. sorted_keys = sorted(t.keys())
  30. # print('排序后的参数为:', sorted_keys)
  31. # 创建一个新的有序字典
  32. sorted_dict = {key: str(t[key]) for key in sorted_keys}
  33. return sorted_dict
  34. def get_sign(url_: str):
  35. """
  36. 定义 get_sign 函数,用于生成 MD5 签名
  37. :param url_: url
  38. :return: nonce, timestamp, md5_hash
  39. """
  40. url_p = return_new_url(url_)
  41. # 生成随机字符串 n 和时间戳 a
  42. n = generate_random_string()
  43. # print('nonce的值为:', n)
  44. a = str(int(time.time() * 1000)) # 当前时间戳(毫秒)
  45. # f = {
  46. # 'timestamp': "1744693310566", # 时间戳
  47. # 'nonce': "x0hs3t1hwyvsd5foi7dn", # 随机字符串
  48. # 'salt': "1s2JTL0F9u8^=m6-dW]6yLU1T50ppr8m", # 固定盐值
  49. # 'url': "getCardCollageInfoByIdByShare" # 路由标识
  50. # }
  51. f = {
  52. 'timestamp': a, # 时间戳
  53. 'nonce': n, # 随机字符串
  54. 'salt': "1s2JTL0F9u8^=m6-dW]6yLU1T50ppr8m", # 固定盐值
  55. 'url': url_p # 路由标识
  56. }
  57. # 对输入字典进行浅拷贝并排序
  58. sorted_data = sort_asc(f)
  59. # print('排序后的参数为:', sorted_data)
  60. # 将排序后的字典转换为 JSON 字符串
  61. json_string = json.dumps(sorted_data, separators=(',', ':'))
  62. # print('加密前的参数为:', json_string)
  63. # 使用 hashlib 创建 MD5 哈希
  64. md5_hash = hashlib.md5(json_string.encode('utf-8')).hexdigest()
  65. return n, a, md5_hash
  66. # 主程序
  67. if __name__ == "__main__":
  68. url = "https://app.cardplayd.com/app/system/shop/queryShopList"
  69. sign = get_sign(url)
  70. print('加密后的 sign 为:', sign)
  71. # 2b3865f7fc38e94ed0b9f673c3a6a104
  72. # "x0hs3t1hwyvsd5foi7dn" "6531a8d9fb78f5d3969b853cf31fbcd9"