1

I'm trying to encode and decode a byte string using Crypto.Cipher library in Python. The code for encryption is:

message = b'Hello world How are you Have a great day' 
key = pad(b'Hello world', 16)
iv = os.urandom(16)                   
encryptor = AES.new(key, AES.MODE_CFB)  
cipher_text = encryptor.encrypt(message)
print(cipher_text)

The output I get:

b'x\xc1\x8a&\x07c\x98\xdbl@$\xde\xfeG\x80\x00\xb6\xfd\x17\x9d\xb1R\xdd\xcf1\n\xb5\xe6I\x11\xe0\x96\x08E\x11\xa8^\xbf\x1el'

However, when I decrypt the message back, I would expect to get the same message b'Hello world How are you Have a great day'. But, I don't. The code for decryption is:

decryptor = AES.new(key, AES.MODE_CFB, iv=iv)  
msg = decryptor.decrypt(cipher_text)
print(msg)

The output I get:

b'[\xa0\xfd\xab>T\x90)\xd5\xf3\x8a\xbb\xe0;\xff\xdaare you Have a great day'

I was trying to apply decode() function, but it doesn't seem to be working. Could someone please give a hint or give a direction? Thank you.

Ksenija
  • 31
  • 4

1 Answers1

1

The explicitly generated IV iv is used only during decryption, but not during encryption. Thus, a different IV is implicitly generated during encryption, making the IVs different during encryption and decryption. Fix:

encryptor = AES.new(key, AES.MODE_CFB, iv=iv)

Also, do not use a (padded) password as the key. There are password-based key derivation functions for this purpose.