testAES.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. #!/usr/bin/env python35
  2. # -*- coding: utf-8 -*-
  3. # Created by wyy on 2018/3/20 13:48.
  4. import base64
  5. import json
  6. import re
  7. from Crypto.Cipher import AES
  8. #http://tool.chacuo.net/cryptaes
  9. class AESECB:
  10. def __init__(self, key):
  11. self.key = key
  12. self.mode = AES.MODE_ECB
  13. self.bs = 16 # block size
  14. #self.PADDING = lambda s: s + (self.bs - len(s) % self.bs) * chr(self.bs - len(s) % self.bs)只支持英文入参
  15. self.PADDING = lambda s: s + (self.bs - len(s.encode('gbk')) % self.bs) * chr(self.bs - len(s.encode('gbk')) % self.bs)
  16. def encrypt(self, text):
  17. aes = AES.new(self.key, self.mode) # ECB模式无需向量iv
  18. #encrypt_aes = aes.encrypt((self.PADDING(text)).encode(encoding="utf-8"))
  19. encrypt_aes = aes.encrypt((self.PADDING(text)).encode(encoding="gbk"))
  20. # encrypted_base64 = base64.b64encode(encrypt_aes)
  21. #print(encrypted_base64)
  22. #return str(encrypted_base64, encoding='utf-8')
  23. return encrypt_aes
  24. def decrypt(self, text):
  25. aes = AES.new(str.encode(self.key), self.mode) # ECB模式无需向量iv
  26. text += (len(text) % 4) * '='
  27. encrypt_aes = base64.b64decode(text)
  28. data = aes.decrypt(encrypt_aes)
  29. # 去除解码后的非法字符data.decode()
  30. try:
  31. result = re.compile('[\\x00-\\x08\\x0b-\\x0c\\x0e-\\x1f\n\r\t]').sub('', str(data, encoding='utf-8'))
  32. except Exception:
  33. result = '解码失败,请重试!'
  34. return result
  35. def text2hex(_str):
  36. list_hex = []
  37. if isinstance(_str,str):
  38. _str1 = _str.encode()
  39. elif isinstance(_str,bytes):
  40. _str1 = _str
  41. for _hex in map(hex,_str1):
  42. _i = int(_hex[2:],16)
  43. while(True):
  44. a = _i&0xFF
  45. list_hex.append(hex(a)[2:].rjust(2,"0"))
  46. _i = _i >>8
  47. if _i==0:
  48. break
  49. return "".join(list_hex)
  50. if __name__ == '__main__':
  51. key = base64.b64decode('zDXjL5mx5HeUgmsg7HyKLg==') # 密钥长度必须为16、24或32位,分别对应AES-128、AES-192和AES-256
  52. text = "137667617" # 待加密文本
  53. aes = AESECB(key)
  54. #print(aes.encrypt('wyy1221wyy1221'))
  55. #print(aes.decrypt('m9RKpQSCrZ6fF7RuPoyNLA=='))
  56. print(text2hex(aes.encrypt(text)))