|
|
|
@ -13,23 +13,23 @@ class AESUtils:
|
|
|
|
|
else:
|
|
|
|
|
self.key = key
|
|
|
|
|
|
|
|
|
|
def encrypt(self, data: str, mode: str = 'ECB') -> str:
|
|
|
|
|
def encrypt(self, data: str, mode: str = 'ECB') -> (str,str):
|
|
|
|
|
"""加密数据"""
|
|
|
|
|
cipher = self._get_cipher(mode)
|
|
|
|
|
data = pad(data.encode(), AES.block_size) # 填充数据
|
|
|
|
|
ciphertext = cipher.encrypt(data)
|
|
|
|
|
return base64.b64encode(ciphertext).decode()
|
|
|
|
|
return base64.b64encode(ciphertext).decode(),self.key
|
|
|
|
|
|
|
|
|
|
def _get_cipher(self, mode: str) -> AES:
|
|
|
|
|
"""根据模式返回相应的 AES cipher"""
|
|
|
|
|
iv = None
|
|
|
|
|
if mode == 'CBC':
|
|
|
|
|
iv = get_random_bytes(AES.block_size)
|
|
|
|
|
return AES.new(self.key, AES.MODE_CBC, iv), self.key
|
|
|
|
|
return AES.new(self.key, AES.MODE_CBC, iv)
|
|
|
|
|
elif mode == 'CFB':
|
|
|
|
|
return AES.new(self.key, AES.MODE_CFB), self.key
|
|
|
|
|
return AES.new(self.key, AES.MODE_CFB)
|
|
|
|
|
elif mode == 'OFB':
|
|
|
|
|
return AES.new(self.key, AES.MODE_OFB), self.key
|
|
|
|
|
return AES.new(self.key, AES.MODE_OFB)
|
|
|
|
|
else: # 默认是 ECB
|
|
|
|
|
return AES.new(self.key, AES.MODE_ECB), self.key
|
|
|
|
|
return AES.new(self.key, AES.MODE_ECB)
|
|
|
|
|
|
|
|
|
|