SignatureUtils.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. # -*- coding: utf-8 -*-
  2. '''
  3. Created on 2017-12-20
  4. @author: liuqun
  5. '''
  6. import base64
  7. import json
  8. import rsa
  9. from alipay.aop.api.constant.CommonConstants import PYTHON_VERSION_3
  10. from alipay.aop.api.util.StringUtils import *
  11. def get_sign_content(all_params):
  12. sign_content = ""
  13. for (k, v) in sorted(all_params.items()):
  14. value = v
  15. if not isinstance(value, str):
  16. value = json.dumps(value, ensure_ascii=False)
  17. sign_content += ("&" + k + "=" + value)
  18. sign_content = sign_content[1:]
  19. return sign_content
  20. def fill_private_key_marker(private_key):
  21. return add_start_end(private_key, "-----BEGIN RSA PRIVATE KEY-----\n", "\n-----END RSA PRIVATE KEY-----")
  22. def fill_public_key_marker(public_key):
  23. return add_start_end(public_key, "-----BEGIN PUBLIC KEY-----\n", "\n-----END PUBLIC KEY-----")
  24. def sign_with_rsa(private_key, sign_content, charset):
  25. if PYTHON_VERSION_3:
  26. sign_content = sign_content.encode(charset)
  27. private_key = fill_private_key_marker(private_key)
  28. signature = rsa.sign(sign_content, rsa.PrivateKey.load_pkcs1(private_key, format='PEM'), 'SHA-1')
  29. sign = base64.b64encode(signature)
  30. if PYTHON_VERSION_3:
  31. sign = str(sign, encoding=charset)
  32. return sign
  33. def sign_with_rsa2(private_key, sign_content, charset):
  34. if PYTHON_VERSION_3:
  35. sign_content = sign_content.encode(charset)
  36. private_key = fill_private_key_marker(private_key)
  37. signature = rsa.sign(sign_content, rsa.PrivateKey.load_pkcs1(private_key, format='PEM'), 'SHA-256')
  38. sign = base64.b64encode(signature)
  39. if PYTHON_VERSION_3:
  40. sign = str(sign, encoding=charset)
  41. return sign
  42. def verify_with_rsa(public_key, message, sign):
  43. public_key = fill_public_key_marker(public_key)
  44. sign = base64.b64decode(sign)
  45. return bool(rsa.verify(message, sign, rsa.PublicKey.load_pkcs1_openssl_pem(public_key)))