import base64
from Crypto.Cipher import AES
SECRET_KEY = 'TV12LL0931TL9188819V3T29TZ113ZL7' # 此处16|24|32个字符
#SECRET_KEY = '0123456789ABCDEF'
class AES_ENCRYPT(object):
def __init__(self):
self.key = SECRET_KEY
self.mode = AES.MODE_ECB
def pading(self, text):
"""对加密字符的处理"""
return text + (len(self.key) - len(text) % len(self.key)) * chr(len(self.key) - len(text) % len(self.key))
def unpading(self, text):
"""对解密字符的处理"""
return text[0:-ord(text[-1:])]
def _add_to_16(self, s):
s = str.encode(s)
k = len(self.key)
pad_size = k - len(s) % k
s += pad_size * bchr(pad_size)
print(s)
return s
def getKey(self, key):
"""对key的处理,key 的长度 16,24,32"""
key_len = len(key)
if key_len <= 16:
key += "0" * (16 - key_len)
elif 16 < key_len <= 24:
key += "0" * (24 - key_len)
elif key_len <= 32:
key += "0" * (32 - key_len)
else:
key = key[:32]
return key
# 加密函数
def encrypt(self, text):
cryptor = AES.new(self.key.encode("utf-8"), self.mode) # ECB 模式
self.ciphertext = cryptor.encrypt(bytes(self.pading(text), encoding="utf8"))
encrypt_string = str(base64.b64encode(self.ciphertext)).lstrip("b")
return encrypt_string
# 解密函数
def decrypt(self, text):
decode = base64.b64decode(text)
cryptor = AES.new(self.key.encode("utf8"), self.mode) # ECB 模式
plain_text = cryptor.decrypt(decode)
decrypt_string = str(self.unpading(plain_text)).lstrip("b")
return decrypt_string
if __name__ == '__main__':
aes_encrypt = AES_ENCRYPT()
en = "411081199011099234"
print(aes_encrypt.encrypt(en))
print(aes_encrypt.decrypt('wvHKVsssRjJ3FS/nYJW24BeGYD/tQ7d01OgA4zpuTsg='))