python 文件aes加密
时间: 2023-09-02 21:12:02 浏览: 43
以下是使用 Python 进行文件 AES 加密的代码:
```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))
# 读取文件并加密
key = b'mysecretpassword'
encrypt_file(key, 'example.txt')
```
在上述代码中,我们使用了 Python 的 `Crypto` 库进行 AES 加密。`encrypt_file` 函数用于读取指定文件并进行加密,加密过程采用 CBC 模式,使用随机生成的 16 字节 IV 向量。加密后的文件名为原文件名加上 `.enc` 后缀。在加密文件时,我们先将文件大小写入输出文件的开头,然后写入 IV 向量,最后按照指定的块大小(64KB)读取并加密文件数据。