Python AES Decrypt printed with encrypted text
<p>i got a problem with decryption text file that say 'i want to be clear text file'.</p>

<p>the encryption is good work but when i decrypt it's get mixed, clear text and encrypt data.</p>

<p>now i know me writing is a little amateurish.. but i need your help to get it through.
i tried to build it in def functions but it didn't went well..</p>

<p>I'm thinking that the padding in the encryption is the problem, but when i test it on a 16 byte text file it's still was mixed.</p>

<pre><code>#!/usr/bin/env python

from Crypto.Cipher import AES
from Crypto.Protocol.KDF import PBKDF2
from Crypto import Random
import os

file_path = raw_input("Enter File path: ")
if os.path.isdir(file_path):  #check if the path exists
    print "\nFile path founded, continue..\n"
else:
    print "\nFile path is not correct\nExiting.\n"
    exit(0)
file_name = raw_input("Enter File name: ")
full_path =  file_path + file_name
if os.path.isfile(full_path):
    print "\nFile name founded, continue..\n"
else:
    print "\nFile name is not correct\nExiting.\n"
    exit(0)



print "Now encrypt"
key_size = 32 #AES256
iterations = 10000
key = os.urandom(32)
read = open(full_path,'r+')
line = read.readline()
secret = line
length = 16 - (len(secret) % 16) #PKCS7 adds bytes of the length of padding
secret += chr(length) * length
read.close()
salt = Random.new().read(key_size) #salt the hash
iv = Random.new().read(AES.block_size)
derived_key = PBKDF2(key, salt, key_size, iterations)
cipher = AES.new(derived_key, AES.MODE_CBC, iv)

encodedtext = iv + cipher.encrypt(secret)
read = open(full_path, 'w')
read.write(encodedtext)
read.close()


print "Now decrypt"
key_size2 = 32 #AES256
iterations2 = 10000
read2 = open(full_path,'r')
line2 = read2.readline()
secret2 = line2
length2 = 16 - (len(secret2) % 16) #PKCS7 adds bytes of the length of padding
secret2 += chr(length2) * length2
read2.close()
dencodedtext2 = iv + cipher.decrypt(secret2)
read2 = open(full_path, 'w')
read2.write(dencodedtext2)
read2.close()
print "that worked?"
</code></pre>

<p>for the test
i gave a path '/home/****/Dekstop/
and i gave file 'test.txt' with the text 'i want to be clear text file'
and i got this,</p>

<blockquote>
  <p>ææï¢î¸¦ã±£à»¸å¼§æ®²íì»«èãì¢äåç²ï»¿i want to be clear text fileÔÔÔá¡¶ä´áâºé«±ì¤áµê</p>
</blockquote>

<p>why when i print secret2 after 'dencodedtext2 = iv + cipher.decrypt(secret2)' the text is mixed with encryption?
how can i fixed it?
and what im doing so terrible?</p>

<p>thank a head for any kind of help!</p>

<p>There are two major mistakes within the code:</p>

<ul>
<li>the IV needs to be stripped off before (and used during) decryption instead of adding it again to the plaintext; currently your plaintext starts with the IV and then a decrypted IV;</li>
<li>the padding needs to be removed after decryption, not before, currently some padding related muck is still shown at the end.</li>
</ul>

python encryption cryptography aes