一般由前端加密传输,后端负责解密
from Crypto.Cipher import AES
import base64
key = '0123456789ABCDEF'
# 加密
def encrypt(key, plaintext):
aes = AES.new(str.encode(key), AES.MODE_ECB) # 初始化加密器,本例采用ECB加密模式
# 填充明文以适应AES块大小
block_size = AES.block_size
padding_length = block_size - (len(plaintext) % block_size)
padded_plaintext = plaintext + chr(padding_length) * padding_length
encrypted_bytes = aes.encrypt(str.encode(padded_plaintext)) # 加密
encrypted_text = base64.b64encode(encrypted_bytes).decode('utf-8') # 将加密结果转为Base64编码
return encrypted_text
plaintext = 'zhubajie'
pwd_en = encrypt(key, plaintext)
print(pwd_en) # 7Pd/iNJShKKIUc7pBANWhw==
# 解密
def decrypt(key, ct):
aes = AES.new(str.encode(key), AES.MODE_ECB) # 初始化加密器,本例采用ECB加密模式
decrypted_text = aes.decrypt(base64.decodebytes(bytes(ct, encoding='utf8'))).decode("utf8") # 解密
decrypted_text = decrypted_text[:-ord(decrypted_text[-1])] # 去除多余补位
return decrypted_text
pwd_de = decrypt(key, pwd_en)
print(pwd_de) # zhubajie