Im trying to encrypt every line of the file test.txt the function encrypt() will output basically the text all jumbled up. For an end of year project in my computer science class. But my problem is when i try to run the code "backwards" with decrypt_all it doesnt work and the file is still corrupted
from Crypto.Cipher import XOR
import base64
import os
def encrypt(key=None, plaintext=None):
if key == None:
key = "This_is_my_hidden_key"
cipher = XOR.new(key)
return base64.b64encode(cipher.encrypt(plaintext))
def decrypt(key=None, ciphertext=None):
if key == None:
key = "This_is_my_hidden_key"
cipher = XOR.new(key)
return cipher.decrypt(base64.b64decode(ciphertext))
#####Run below to encrypt all files in folder and each sub folder#######
def encrypt_all(UselessVariable = None):
root = os.getcwd()
path = os.path.join(root, "targetdirectory")
x=0
for path, subdirs, files in os.walk(root):
for name in files:
openfile = os.path.join(path, name)
print openfile
try:
with open(openfile, 'r+') as a:
encrypted_text = []
for line in a:
encrypted_text.append(decrypt(None, line))
open(openfile,"w").close()
for text in range(len(encrypted_text)):
a.write((str(encrypted_text[text]))+ '\n')
except IOError as e:
print 'Operation failed: %s' % e.strerror
x+=1
print ""
print x
#####Run below to decrypt all files in folder and each sub folder#######
def decrypt_all(UselessVariable = None):
root = os.getcwd()
path = os.path.join(root, "targetdirectory")
x=0
for path, subdirs, files in os.walk(root):
for name in files:
openfile = os.path.join(path, name)
print openfile
try:
with open(openfile, 'r+') as a:
encrypted_text = []
for line in a:
encrypted_text.append(decrypt(None, line))
open(openfile,"w").close()
for text in range(len(encrypted_text)):
a.write((str(encrypted_text[text])))
except IOError as e:
print 'Operation failed: %s' % e.strerror
x+=1
print ""
print x