So I'm trying to make a simple AES encrypt/decrypt system right now in Python... However when it decrypts it has a bunch of /xxx/xxx/xxx/xxx/ in front of the decrypted string. How do I clean it and make it print only the plaintext.
My code is:
import base64
from Crypto.Cipher import AES
from Crypto import Random
key = b'Sixteen byte key'
iv = Random.new().read(AES.block_size)
cipher = AES.new(key, AES.MODE_CFB, iv)
msg = iv + cipher.encrypt(b'Attack at dawn...')
print (msg)
print (base64.b64encode(msg))
print (cipher.decrypt(msg))
The output of decrypt
looks like this:
b'\xfb\xb8\xf0\xc3\xffH\xfc~\x19[\xecy?\xf8\xcc\x80Attack at dawn...'
The initialization vector (IV) is part of your encrypted message (msg
), but the ciphertext itself should contain the IV. This means that you have to remove the IV before decrypting, i.e. like this:
cipher.decrypt(msg[16:])
Next issue is that you shouldn't use the same AES
instance for encryption and decryption. The AES
instance contains internal buffers that cannot be easily refreshed.
key = b'Sixteen byte key'
# encryption
iv = Random.new().read(AES.block_size)
cipher = AES.new(key, AES.MODE_CFB, iv)
msg = iv + cipher.encrypt(b'Attack at dawn...')
print (msg)
print (base64.b64encode(msg))
# decryption
cipher = AES.new(key, AES.MODE_CFB, msg[:16])
print (cipher.decrypt(msg[16:]))
However when it decrypts it has a bunch of /xxx/xxx/xxx/xxx/ in front of the decrypted string.
You have much luck that you see the decrypted string at all at the end. This is only because the IV is prepended to the message and the inner workings of the CFB mode of operation. If you would have used the CTR mode, this would have looked much different.