Search code examples
pythonencryptionpycrypto

Whenever I use with pycrypto it deletes the file


I found some code online that is supposed to encrypt and decrypt files, but whenever I use it, it encrypts the file then when decrypting the file, it just deletes the file when it's decrypting it

The program gives me different outputs when the text document I'm testing it on is empty or has words in it after the file is encrypted, so I know the deletion happens when the file is decrypted, I just don't know where in the code this happens.

Here's the whole program

import os
from Crypto.Cipher import AES
from Crypto.Hash import SHA256
from Crypto import Random

def encrypt(key, filename):
    chunksize = 64*1024
    outputFile = filename
    filesize = str(os.path.getsize(filename)).zfill(16)
    IV = Random.new().read(16)

    encryptor = AES.new(key, AES.MODE_CBC, IV)

    with open(filename, 'rb') as infile:
        with open(outputFile, 'wb') as outfile:
            outfile.write(filesize.encode('utf-8'))
            outfile.write(IV)

            while True:
                chunk = infile.read(chunksize)

                if len(chunk) == 0:
                    break
                elif len(chunk) % 16 != 0:
                    chunk += b' ' * (16 - (len(chunk) % 16))

                outfile.write(encryptor.encrypt(chunk))


def decrypt(key, filename):
    chunksize = 64*1024
    outputFile = filename

    with open(filename, 'rb') as infile:
        filesize = int(infile.read(16))
        IV = infile.read(16)
        decryptor = AES.new(key, AES.MODE_CBC, IV)
        with open(outputFile, 'wb') as outfile:
            while True:
                chunk = infile.read(chunksize)
                if len(chunk) == 0:
                    break
                outfile.write(decryptor.decrypt(chunk))
            outfile.truncate(filesize)


def getKey(password):
    hasher = SHA256.new(password.encode('utf-8'))
    return hasher.digest()

password = 'hello'
filename = r'C:\Users\user\Desktop\test.txt'
encrypt(getKey(password), filename)
print("encrypted!")
decrypt(getKey(password), filename)
print("Derypted!.")

I would like to keep the file I'm trying to decrypt intact.


Solution

  • You use the same file as input and output .. that's a bad idea:

    def decrypt(key, filename):
        chunksize = 64*1024
        outputFile = filename                    << output
    
        with open(filename, 'rb') as infile:     << & input is the same