使用AES对文件夹里的文件进行加密的python代码实现
时间: 2024-05-08 13:18:46 浏览: 26
我可以回答您的问题。
以下是使用Python中的AES模块对文件夹中的文件进行加密的示例代码:
```python
import os
from Crypto.Cipher import AES
# 设置加密密钥,长度必须为16、24或32位
key = b'1234567890123456'
# 加密函数
def encrypt_file(filename):
# 生成一个随机的初始向量
iv = os.urandom(16)
# 读取文件内容
with open(filename, 'rb') as f:
data = f.read()
# 使用AES CBC模式进行加密
cipher = AES.new(key, AES.MODE_CBC, iv)
ciphertext = cipher.encrypt(data)
# 将加密后的数据写入新文件
with open(filename + '.enc', 'wb') as f:
f.write(iv + ciphertext)
# 解密函数
def decrypt_file(filename):
# 读取加密文件内容
with open(filename, 'rb') as f:
data = f.read()
# 提取初始向量和密文
iv = data[:16]
ciphertext = data[16:]
# 使用AES CBC模式进行解密
cipher = AES.new(key, AES.MODE_CBC, iv)
plaintext = cipher.decrypt(ciphertext)
# 将解密后的数据写入新文件
with open(filename[:-4], 'wb') as f:
f.write(plaintext)
# 遍历文件夹中的文件,并对其进行加密
def encrypt_folder(path):
for root, dirs, files in os.walk(path):
for filename in files:
encrypt_file(os.path.join(root, filename))
# 遍历加密后的文件夹中的文件,并对其进行解密
def decrypt_folder(path):
for root, dirs, files in os.walk(path):
for filename in files:
if filename.endswith('.enc'):
decrypt_file(os.path.join(root, filename))
# 测试加密和解密功能
encrypt_folder('/path/to/folder')
decrypt_folder('/path/to/folder')
```
以上代码使用AES CBC模式对文件夹中的文件进行加密,加密后的文件将被保存为原始文件名加上'.enc'的形式。解密时需要使用相同的密钥。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)