你沒有指定,但你的代碼看起來像你使用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))