# linux系统 pip install pycrypto
# Windows pip3 install -i https://pypi.douban.com/simple pycryptodome 找到文件所在目录 将文件夹名"crypto" 修改为"Crypto"
from Crypto.Cipher import AES
class AesCbc:
__instance = None
# 单例模式
def __new__(cls, *args, **kwargs):
if not cls.__instance:
cls.__instance = super().__new__(cls, *args, **kwargs)
return cls.__instance
def __init__(self):
# key:秘钥,大小为16byte/24byte/32byte----AES-128/AES-192/AES-256/
self.key = 'xiwenr&dstaTGpRw'.encode('utf-8')
# vi:初始向量,大小为16byte
self.iv = b'xiwenr&drhGW5hN3'
self.mode = AES.MODE_CBC
# 如果text不足16位的倍数就用空格补足为16位
@staticmethod
def add_to_16(text):
if len(text.encode('utf-8')) % 16:
add = 16 - (len(text.encode('utf-8')) % 16)
else:
add = 0
text = text + ('\0' * add)
return text.encode('utf-8')
# 加密函数
def encrypt(self, text):
text = self.add_to_16(text)
cryptos = AES.new(self.key, self.mode, self.iv)
cipher_text = cryptos.encrypt(text)
# 因为AES加密后的字符串不一定是ascii字符集的,输出保存可能存在问题,所以这里转为16进制字符串
return b2a_hex(cipher_text).decode()
# 解密后,去掉补足的空格用strip() 去掉
def decrypt(self, text):
cryptos = AES.new(self.key, self.mode, self.iv)
plain_text = cryptos.decrypt(a2b_hex(text))
return bytes.decode(plain_text).rstrip('\0')