使用python写一个脚本,需求是对文件夹进行加密
时间: 2024-03-27 09:38:01 浏览: 226
好的,为了加密文件夹,我们可以使用Python中的PyCrypto库。以下是实现该需求的基本步骤:
1. 生成密钥:我们需要生成一个密钥,用于加密和解密文件夹。可以使用PyCrypto库中的Crypto.Random模块来生成一个长度为16字节的随机字符串,作为我们的密钥。
2. 加密文件夹:我们可以使用PyCrypto库中的Crypto.Cipher模块来加密文件夹。对于每个文件,我们可以使用密钥来生成一个加密器,并使用加密器来加密文件的内容。加密后的文件可以保存到一个新的文件夹中。
3. 解密文件夹:解密文件夹的过程与加密文件夹的过程相似。对于每个加密后的文件,我们可以使用密钥来生成一个解密器,并使用解密器来解密文件的内容。解密后的文件可以保存到一个新的文件夹中。
以下是一个示例代码,用于加密和解密文件夹:
```python
from Crypto.Cipher import AES
import os
import random
import string
def generate_key(length):
"""生成指定长度的密钥"""
return ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(length))
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.encode('utf-8'), AES.MODE_CBC, iv)
filesize = os.path.getsize(in_filename)
with open(in_filename, 'rb') as infile, 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 decrypt_file(key, in_filename, out_filename=None, chunksize=24*1024):
"""解密文件"""
if not out_filename:
out_filename = os.path.splitext(in_filename)[0]
with open(in_filename, 'rb') as infile:
origsize = int.from_bytes(infile.read(8), byteorder='big')
iv = infile.read(16)
decryptor = AES.new(key.encode('utf-8'), AES.MODE_CBC, iv)
with open(out_filename, 'wb') as outfile:
while True:
chunk = infile.read(chunksize)
if len(chunk) == 0:
break
outfile.write(decryptor.decrypt(chunk))
outfile.truncate(origsize)
def encrypt_folder(key, in_folder, out_folder=None):
"""加密文件夹"""
if not out_folder:
out_folder = in_folder + '.enc'
os.makedirs(out_folder, exist_ok=True)
for root, _, filenames in os.walk(in_folder):
for filename in filenames:
in_filename = os.path.join(root, filename)
out_filename = os.path.join(out_folder, os.path.relpath(in_filename, in_folder))
encrypt_file(key, in_filename, out_filename)
def decrypt_folder(key, in_folder, out_folder=None):
"""解密文件夹"""
if not out_folder:
out_folder = os.path.splitext(in_folder)[0]
os.makedirs(out_folder, exist_ok=True)
for root, _, filenames in os.walk(in_folder):
for filename in filenames:
in_filename = os.path.join(root, filename)
out_filename = os.path.join(out_folder, os.path.relpath(in_filename, in_folder))
decrypt_file(key, in_filename, out_filename)
# 示例用法
key = generate_key(16)
encrypt_folder(key, '/path/to/folder')
decrypt_folder(key, '/path/to/folder.enc')
```
请注意,此示例代码仅用于演示目的,实际使用时需要进行更多的错误处理和安全性检查。
阅读全文
相关推荐















