python 文件加密
时间: 2023-07-15 14:15:15 浏览: 53
在 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 + '.encrypted'
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 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, 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)
# 使用示例
key = b'secret_key_12345'
# 加密文件
encrypt_file(key, 'test.txt')
# 解密文件
decrypt_file(key, 'test.txt.encrypted')
```
在上面的示例中,我们生成一个 16 字节的随机向量(iv),并使用 AES 加密算法和 CBC 模式进行加密。加密后的文件包含原始文件的大小(8 字节),随机向量和加密后的数据。解密时,我们读取这些数据并使用相同的密钥和向量进行解密,然后截断数据以匹配原始文件的大小。