123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869 |
- #!/usr/bin/env python35
- # -*- coding: utf-8 -*-
- # Created by wyy on 2018/3/20 13:48.
- import base64
- import json
- import re
- from Crypto.Cipher import AES
- #http://tool.chacuo.net/cryptaes
- class AESECB:
- def __init__(self, key):
- self.key = key
- self.mode = AES.MODE_ECB
- self.bs = 16 # block size
- #self.PADDING = lambda s: s + (self.bs - len(s) % self.bs) * chr(self.bs - len(s) % self.bs)只支持英文入参
- self.PADDING = lambda s: s + (self.bs - len(s.encode('gbk')) % self.bs) * chr(self.bs - len(s.encode('gbk')) % self.bs)
- def encrypt(self, text):
- aes = AES.new(self.key, self.mode) # ECB模式无需向量iv
- #encrypt_aes = aes.encrypt((self.PADDING(text)).encode(encoding="utf-8"))
- encrypt_aes = aes.encrypt((self.PADDING(text)).encode(encoding="gbk"))
- # encrypted_base64 = base64.b64encode(encrypt_aes)
- #print(encrypted_base64)
- #return str(encrypted_base64, encoding='utf-8')
- return encrypt_aes
- def decrypt(self, text):
- aes = AES.new(str.encode(self.key), self.mode) # ECB模式无需向量iv
- text += (len(text) % 4) * '='
- encrypt_aes = base64.b64decode(text)
- data = aes.decrypt(encrypt_aes)
- # 去除解码后的非法字符data.decode()
- try:
- result = re.compile('[\\x00-\\x08\\x0b-\\x0c\\x0e-\\x1f\n\r\t]').sub('', str(data, encoding='utf-8'))
- except Exception:
- result = '解码失败,请重试!'
- return result
- def text2hex(_str):
- list_hex = []
- if isinstance(_str,str):
- _str1 = _str.encode()
- elif isinstance(_str,bytes):
- _str1 = _str
- for _hex in map(hex,_str1):
- _i = int(_hex[2:],16)
- while(True):
- a = _i&0xFF
- list_hex.append(hex(a)[2:].rjust(2,"0"))
- _i = _i >>8
- if _i==0:
- break
- return "".join(list_hex)
- if __name__ == '__main__':
- key = base64.b64decode('zDXjL5mx5HeUgmsg7HyKLg==') # 密钥长度必须为16、24或32位,分别对应AES-128、AES-192和AES-256
- text = "137667617" # 待加密文本
- aes = AESECB(key)
- #print(aes.encrypt('wyy1221wyy1221'))
- #print(aes.decrypt('m9RKpQSCrZ6fF7RuPoyNLA=='))
- print(text2hex(aes.encrypt(text)))
|