0

I have a text file containing the following text:

message.txt

this is my secret message

I wrote a small python code to read that file and encode it using Crypto.Cipher

from Crypto.Cipher import DES
f = open('message.txt','rb')
text = f.read()
f.close()

iv   = Random.get_random_bytes(8)
des1 = DES.new('01234567', DES.MODE_CFB, iv)

secret = des1.encrypt(text)  
print("Encrypted text: " + secret)   

output:

Encrypted text: Å..GH.ÿì.Vs~ö.~.wôÇ.k5â

I then saved the output string to a text file:

w = open('encrypted.txt','wb')
w.write(secret)
w.close()

Then I tried to open the same encrypted file and decrypt the content back to its original message:

d = open('encrypted.txt','rb')
secret = d.read()
d.close()

text = des1.decrypt(secret)
print("decreypted text is: " + text)

output:

decrypted text is: óF2â.}1Úmy secret message

It is very strange that the encryption works partially. I was under the impression that you would either encryption would produce the whole original message intact, or it would yield an unreadable gibberish text. But never expected a mixture of the two.

What am I doing wrong?

*Edit: I have edited my question: I always read binary and write binary. The half decrypted output happens when I read/write binary. When I don't read binary, the output is completely gibberish.

Ahmad
  • 12,336
  • 6
  • 48
  • 88
  • 1
    I don't know much Python, but you should read and write **binary**, not text, as you say you are in your question. *From bytes to strings does not a happy cryptographer make.* – Luke Joshua Park Mar 19 '17 at 06:30
  • @LukePark I have edited my question. I already work in `binary` mode, but forgot to indicate that in my question. – Ahmad Mar 19 '17 at 06:49
  • 1
    The internal IV/counter buffer behaves the same way in CFB as in CTR mode. It must be reinitialized with the same IV as was used for encryption. The IV is not secret, so you can send it along with the ciphertext. Usually, it is simply prepended to the ciphertext and sliced off before decryption. – Artjom B. Mar 19 '17 at 09:37
  • In other words, create a new DES object for decryption, and it will work. – Roland Smith Mar 19 '17 at 09:43

0 Answers0