用Python写一个批量文件加密算法
时间: 2024-03-28 14:12:17 浏览: 66
当然,我可以帮你完成这个问题。你需要使用python中的pycryptodome库来实现批量文件加密。下面是一个简单的实现:
```python
from Crypto.Cipher import AES
import os
def encrypt_file(key, in_filename, out_filename=None, chunksize=64*1024):
if not out_filename:
out_filename = in_filename + '.enc'
iv = os.urandom(16)
encryptor = AES.new(key, AES.MODE_CBC, iv)
filesize = os.path.getsize(in_filename)
with open(in_filename, 'rb') as infile:
with open(out_filename, 'wb') as outfile:
outfile.write(filesize.to_bytes(8, byteorder='big'))
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 encrypt_files_in_folder(key, folder_path):
for folder_name, subfolders, filenames in os.walk(folder_path):
for filename in filenames:
in_file_path = os.path.join(folder_name, filename)
encrypt_file(key, in_file_path)
os.remove(in_file_path) # 加密后删除原文件
```
上面的代码使用AES算法对文件进行加密,加密模式为CBC,加密后的文件名为原文件名加上".enc"后缀。你可以使用`encrypt_file(key, in_filename, out_filename)`函数来对单个文件进行加密,也可以使用`encrypt_files_in_folder(key, folder_path)`函数来批量加密一个目录下的所有文件。其中`key`是加密密钥,可以是任意长度的bytes类型。
阅读全文