可以在明文后面添加填充,使其长度成为16的倍数。
示例代码:
from Crypto.Cipher import AES
import base64
def aes_encrypt(key, data):
cipher = AES.new(key.encode("utf8"), AES.MODE_ECB)
data = data.encode("utf8")
# 填充
pad_len = 16 - len(data) % 16
data += pad_len * chr(pad_len).encode()
ciphertext = cipher.encrypt(data)
return base64.b64encode(ciphertext).decode()
def aes_decrypt(key, data):
cipher = AES.new(key.encode("utf8"), AES.MODE_ECB)
ciphertext = base64.b64decode(data)
plaintext = cipher.decrypt(ciphertext)
# 去除填充
pad_len = plaintext[-1]
plaintext = plaintext[:-pad_len]
return plaintext.decode()
上一篇:AES加密密钥