简体   繁体   中英

I am trying to use pycrypto to learn about AES and I do not know what I am doing wrong

This is the code I am using to teach myself how AES works. It is supposed to produce the encrypted message an then produce the decrypted message right after it. If anyone can help me figure out what I did wrong, it would be greatly appreciated.

from Crypto.Cipher import AES

data = input(' --> ')
data = bytes(data, encoding='utf-8')

key = b'Sixteen byte key'

cipher = AES.new(key, AES.MODE_EAX)
nonce = cipher.nonce

ciphertext = cipher.encrypt_and_digest(data)

print(ciphertext)

ciphertext = str(ciphertext)
ciphertext = bytes(ciphertext, encoding='utf-8')

key = b'Sixteen byte key'
cipher = AES.new(key, AES.MODE_EAX, nonce=nonce)

plaintext = cipher.decrypt(ciphertext)

print('\n')
print(plaintext)

The only bytes that you should treat as a string are the bytes that have been encoded as a string in the first place. As ciphertext contains random bytes, there will likely be bytes that do not represent a character - almost any encoding has unused / reserved byte values and / or unprintable characters. If you want to convert ciphertext to actual text, you should use a (binary-to-text) encoding such as base 64.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM