这个脚本是xor加密函数,如果加密小文件,是好的,但是我尝试打开一个大文件(大约5GB)的错误信息:
"OverflowError:大小不适合于int“,打开速度太慢。
任何人都可以帮我优化我的脚本,谢谢。
from Crypto.Cipher import XOR
import base64
import os
def encrypt():
enpath = "D:\\Software"
key = 'vinson'
for files in os.listdir(enpath):
os.chdir(enpath)
with open(files,'rb') as r:
print ("open success",files)
data = r.read()
print ("loading success",files)
r.close()
cipher = XOR.new(key)
encoding = base64.b64encode(cipher.encrypt(data))
with open(files,'wb+') as n:
n.write(encoding)
n.close()发布于 2019-03-18 11:38:11
请扩展我的注释:您不希望将文件一次性读取到内存中,而是在较小的块中处理它。
对于任何生产级密码(哪个异或绝对不是),如果源数据不是密码块大小的倍数,则还需要处理填充输出文件。这个脚本不处理这个问题,因此可以断言块大小。
此外,我们不再是不可逆转的(嗯,除了XOR密码实际上是可直接可逆的)用加密版本覆盖文件。(如果您想这样做,最好只是添加代码以删除原始文件,然后将加密的文件重命名到它的位置。这样你就不会得到半写半加密的文件。)
另外,我删除了无用的Base64编码。
但是-不要用这个代码来做任何严肃的事情。请不要。朋友不要把自己的密室卷起来。
from Crypto.Cipher import XOR
import os
def encrypt_file(cipher, source_file, dest_file):
# this toy script is unable to deal with padding issues,
# so we must have a cipher that doesn't require it:
assert cipher.block_size == 1
while True:
src_data = source_file.read(1048576) # 1 megabyte at a time
if not src_data: # ran out of data?
break
encrypted_data = cipher.encrypt(src_data)
dest_file.write(encrypted_data)
def insecurely_encrypt_directory(enpath, key):
for filename in os.listdir(enpath):
file_path = os.path.join(enpath, filename)
dest_path = file_path + ".encrypted"
with open(file_path, "rb") as source_file, open(dest_path, "wb") as dest_file:
cipher = XOR.new(key)
encrypt_file(cipher, source_file, dest_file)https://stackoverflow.com/questions/55220099
复制相似问题