0

So I am using pycryptodome to encrypt a message using a secret key with AES. I want to then, as a test, decrypt the encrypted message using AES with the same secret key. I have done that here, but the result of the decrypted message is not the same as the encrypted message. Maybe I am misunderstanding how AES works, but I would assume that I should be able to decrypt a message encrypted with AES if I have the same secret key, but it would appear that I'm wrong. How do I make this work properly?

 finalCipher = AES.new(sKey, AES.MODE_CFB)
 message = input()
 #Encrypt the message using the cipher
 enMessage = message.encode('utf-8')
 encMessage = finalCipher.encrypt(enMessage)
 print(encMessage) 

 #Create a new cipher to decrypt the encrypted message, using the same key
 otherCipher = AES.new(sKey, AES.MODE_CFB)
 print(otherCipher.decrypt(encMessage))
Jason Garvey
  • 39
  • 1
  • 5

1 Answers1

2

I realized that I need more than just the original secret key to create a cipher that can decrypt messages encrypted using the original cipher. The original cipher I created has an attribute "iv" that I need to use in the constructor of the new cipher in order to be able to use it to decrypt properly, by doing this instead:

 finalCipher = AES.new(sKey, AES.MODE_CFB)
 message = input()
 #Encrypt the message using the cipher
 enMessage = message.encode('utf-8')
 encMessage = finalCipher.encrypt(enMessage)
 print(encMessage) 

 #Create a new cipher to decrypt the encrypted message, using the same key
 otherCipher = AES.new(sKey, AES.MODE_CFB, finalCipher.iv)
 print(otherCipher.decrypt(encMessage))
Jason Garvey
  • 39
  • 1
  • 5
  • Now learn that you need encoding and decoding of the ciphertext for store and transmission like base64. – kelalaka Feb 13 '21 at 08:49
  • Keep in mind that the IV is not secret. In only needs to be unique when used with CFB mode and the same key. We usually prepend it to the ciphertext and slice it off before decryption. – Artjom B. Feb 13 '21 at 09:36