我在网上找到了一些应该用来加密和解密文件的代码,但是每当我使用它时,它都会加密文件,然后在解密文件时,它只是在解密文件时删除了文件
当我正在测试的文本文档为空或在文件加密后在其中包含单词时,该程序会提供不同的输出,所以我知道在解密文件时会发生删除,我只是不知道在代码中的什么地方发生。
这是整个程序
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!.")
我想保留我尝试解密的文件。
答案 0 :(得分:1)
您使用与输入和输出相同的文件..这是个坏主意:
def decrypt(key, filename):
chunksize = 64*1024
outputFile = filename << output
with open(filename, 'rb') as infile: << & input is the same