Reputation: 1
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"
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?"
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!
Upvotes: 0
Views: 560
Reputation: 94058
There are two major mistakes within the code:
Upvotes: 1