每当我使用 pycrypto 时,它都会删除文件

Whenever I use with pycrypto it deletes the file

我在网上找到了一些应该加密和解密文件的代码,但是每当我使用它时,它都会加密文件然后在解密文件时,它只是在解密时删除文件

当我测试它的文本文档是空的或在文件被加密后有文字时,程序会给我不同的输出,所以我知道文件被解密时删除发生了,我只是不知道'不知道在代码的什么地方发生了这种情况。

这是整个程序

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!.")

我想完整地保留我尝试解密的文件。

您使用同一个文件作为输入和输出..这是个坏主意:

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

    with open(filename, 'rb') as infile:     << & input is the same