EncryptUtils.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. # -*- coding: utf-8 -*-
  2. '''
  3. Created on 2017-12-20
  4. @author: liuqun
  5. '''
  6. import base64
  7. from alipay.aop.api.constant.CommonConstants import PYTHON_VERSION_3
  8. from alipay.aop.api.exception.Exception import RequestException
  9. from Crypto.Cipher import AES
  10. BLOCK_SIZE = AES.block_size
  11. pad = lambda s, length: s + (BLOCK_SIZE - length % BLOCK_SIZE) * chr(BLOCK_SIZE - length % BLOCK_SIZE)
  12. unpad = lambda s: s[:-ord(s[len(s) - 1:])]
  13. def encrypt_content(content, encrypt_type, encrypt_key, charset):
  14. if "AES" == encrypt_type.upper():
  15. return aes_encrypt_content(content, encrypt_key, charset)
  16. raise RequestException("当前不支持该算法类型encrypt_type=" + encrypt_type)
  17. def aes_encrypt_content(content, encrypt_key, charset):
  18. length = None
  19. if PYTHON_VERSION_3:
  20. length = len(bytes(content, encoding=charset))
  21. else:
  22. length = len(bytes(content))
  23. padded_content = pad(content, length)
  24. iv = '\0' * BLOCK_SIZE
  25. cryptor = AES.new(base64.b64decode(encrypt_key), AES.MODE_CBC, iv)
  26. encrypted_content = cryptor.encrypt(padded_content)
  27. encrypted_content = base64.b64encode(encrypted_content)
  28. if PYTHON_VERSION_3:
  29. encrypted_content = str(encrypted_content, encoding=charset)
  30. return encrypted_content
  31. def decrypt_content(encrypted_content, encrypt_type, encrypt_key, charset):
  32. if "AES" == encrypt_type.upper():
  33. return aes_decrypt_content(encrypted_content, encrypt_key, charset)
  34. raise RequestException("当前不支持该算法类型encrypt_type=" + encrypt_type)
  35. def aes_decrypt_content(encrypted_content, encrypt_key, charset):
  36. encrypted_content = base64.b64decode(encrypted_content)
  37. iv = '\0' * BLOCK_SIZE
  38. cryptor = AES.new(base64.b64decode(encrypt_key), AES.MODE_CBC, iv)
  39. content = unpad(cryptor.decrypt(encrypted_content))
  40. if PYTHON_VERSION_3:
  41. content = content.decode(charset)
  42. return content