Python AES Decrypt printed with encrypted text

QuestionsCategory: QuestionsPython AES Decrypt printed with encrypted text
Brightn-n-Fresh Staff asked 2 years ago

i got a problem with decryption text file that say 'i want to be clear text file'.

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

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..

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.

#!/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"
    print "\nFile path is not correct\nExiting.\n"
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"
    print "\nFile name is not correct\nExiting.\n"

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
salt = #salt the hash
iv =
derived_key = PBKDF2(key, salt, key_size, iterations)
cipher =, AES.MODE_CBC, iv)

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

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
dencodedtext2 = iv + cipher.decrypt(secret2)
read2 = open(full_path, 'w')
print "that worked?"

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,

悑晍㱣໸弧殲턕컫聅㇛좎䀋傖粁i want to be clear text fileԊԅԅᡶ䴈ᚖ↺髱준Ⴕꂛ

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?

thank a head for any kind of help!