你没有指定,但你的代码看起来像你使用ECB模式。下面是一个简短的示例代码,我写了一个笑脸挑战,稍作修改以更好地适合您的示例代码。确保您的密钥长度为16个字节。另外,纯文本必须是16个字节的倍数。另一个挑战是你实现了一个填充函数。
需要注意的另一件事是,在加密数据后,最安全的方式是使用某种编码进行存储,通常使用Base64。然后,当你去解密它时,base64首先解码数据。
from Crypto.Cipher import AES
import base64
def ecb_encrypt(message, key):
""" Encrypts a message in AES ECB mode with a given key
ACCEPTS: Two strings, the plaintext message and the key
RETURNS: A bytes string of base64 encoded ciphertext
"""
aes = AES.new(key, AES.MODE_ECB)
return base64.b64encode(aes.encrypt(message)).decode()
def ecb_decrypt(encrypted, key):
""" Decrypts a ciphertext in AES ECB mode with a given key
ACCEPTS: Two strings, the base64 encoded ciphertext and the key
RETURNS: A bytes string of the plaintext message
"""
aes = AES.new(key, AES.MODE_ECB)
return aes.decrypt(base64.b64decode(encrypted))
if __name__ == "__main__":
Key = "0000000000000000"
plain_text = "1010101110101011"
cipher_text = ecb_encrypt(plain_text, Key)
decrypted_pt = ecb_decrypt(cipher_text, Key).decode()
print("Original message: {}".format(plain_text))
print("Encrypted message: {}".format(cipher_text))
print("Decrypted message: {}".format(decrypted_pt))