这个脚本是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()
答案 0 :(得分:0)
根据我的评论进行扩展:您不想一次将文件全部读入内存,而是以较小的块进行处理。
对于任何生产级密码(which XOR is definitely not),如果源数据不是密码块大小的倍数,您还需要处理填充输出文件。该脚本没有处理这个问题,因此断言了块大小。
此外,我们不再是不可逆的(好吧,除了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)