![](/img/trans.png)
[英]How can I encrypt .docx files with AES & pycrypto without corrupting the files
[英]python Pycrypto how can I encrypt files and not corrupt them
我已经处理这个问题已有一段时间了。
当我尝试使用PyCrypto加密文件时。 我可以对其进行加密和解密(到目前为止仅适用于图像)。 问题是当我加密并尝试打开它时,该图像已损坏。 如何修复它,以便在加密后仍可以运行该程序或查看图像?
这是加密代码:
from Crypto.Cipher import AES
from Crypto.Hash import SHA256
from Crypto import Random
import os
def Encryption(Key, filename):
chunksize = 64*1024
outputFile = "[CryptoReady]"+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))
加密文件时,其内容通过算法运行,并且内容会更改。 如果您的文件是JPEG,则如果您尝试使用文件查看器打开它的标头,它的标题也会更改,从而使其看起来像已损坏。
但是,幕后发生的事情是它们刚刚从X
变成了Y
要将其带回来并让图像查看器轻松打开它,您将需要使用适当的密钥通过解密算法来运行文件。 这样,您的Y
类型将被完全转换回X
类型,您将能够读取它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.