import base64
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
class AESCipher:
"""AES加解密类(字符串)"""
def __init__(self, key, iv):
"""
初始化
:param key: 密钥(16/24/32字节对应的AES-128/192/256)
"""
if isinstance(key, str):
key = key.encode('utf-8')
if len(key) not in [16, 24, 32]:
raise ValueError("密钥长度必须是16、24或32字节")
self.key = key
self.iv = iv.encode('utf-8')
def encrypt(self, text):
"""
加密字符串
:param text: 要加密的字符串
:return: base64编码的密文字符串
"""
result = None
try:
if isinstance(text, str):
text = text.encode('utf-8')
cipher = AES.new(self.key, AES.MODE_CBC, self.iv)
encrypted = cipher.encrypt(pad(text, AES.block_size))
result = base64.b64encode(encrypted).decode('utf-8')
except Exception as e:
print(f"加密失败: {str(e)}")
return result
def decrypt(self, text):
"""
解密字符串
:param text: base64编码的密文字符串
:return: 解密后的明文字符串
"""
result = None
try:
encrypted = base64.b64decode(text)
cipher = AES.new(self.key, AES.MODE_CBC, self.iv)
decrypted = unpad(cipher.decrypt(encrypted), AES.block_size)
result = decrypted.decode('utf-8')
except Exception as e:
print(f"解密失败: {str(e)}")
return result
KEY = "99999999999999999999999999999999"
IV = "123456789012345x"
aes_cipher = AESCipher(KEY, IV)