Sign.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import hashlib
  2. import json
  3. import base64
  4. import sys
  5. from collections import OrderedDict
  6. from Crypto.PublicKey import RSA
  7. from Crypto.Hash import MD5, SHA1, SHA256
  8. from Crypto.Signature import PKCS1_v1_5 as Signature_PKC
  9. def main():
  10. # 从标准输入读取JSON字符串
  11. input_json = sys.stdin.read().strip()
  12. # 解析JSON数据
  13. input_data = json.loads(input_json)
  14. # 从输入数据中获取参数
  15. req_body_data = input_data["reqBodyData"]
  16. timestamp = input_data["timestamp"]
  17. appId = input_data["appId"]
  18. appKey = input_data["appKey"]
  19. # 按照阿拉伯字符排序
  20. jsonstr = json.dumps(req_body_data, sort_keys=True,separators=(',',':'), ensure_ascii=False)
  21. data = dict()
  22. data["appId"] = appId
  23. data["timestamp"] = timestamp
  24. data["bizData"] = jsonstr
  25. #计算md5值
  26. m = hashlib.md5()
  27. m.update(jsonstr.encode('utf-8'))
  28. # 二进制数据字符串值
  29. md5_str = m.hexdigest()
  30. sign_str = '%s%s%s%s' % (jsonstr, md5_str, appId, timestamp)
  31. # 打印签名值
  32. private_keyBytes = base64.b64decode(appKey)
  33. rsakey = RSA.importKey(private_keyBytes)
  34. signer = Signature_PKC.new(rsakey)
  35. # 根据SHA256算法处理签名内容data
  36. sha_data = SHA1.new(sign_str.encode("utf-8"))
  37. #sha_data = SHA1.new(sign_str)
  38. # 私钥进行签名
  39. signature = base64.b64encode(signer.sign(sha_data))
  40. # 输出签名结果
  41. print(signature)
  42. if __name__ == "__main__":
  43. main()