在自动化下载过程中,处理文件加密和解密是一个重要的环节,尤其是在涉及敏感数据或需要保护版权的内容时。以下是一些处理文件加密和解密的常见方法和步骤:
以下是一个使用 Python 和 cryptography 库进行 AES 加密和解密的示例:
python复制from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend
import os
def encrypt_file(key, input_file, output_file):
iv = os.urandom(16) # 生成随机的初始向量
cipher = Cipher(algorithms.AES(key), modes.CFB(iv), backend=default_backend())
encryptor = cipher.encryptor()
with open(input_file, 'rb') as f:
plaintext = f.read()
with open(output_file, 'wb') as f:
f.write(iv) # 将初始向量写入文件
f.write(encryptor.update(plaintext) + encryptor.finalize())
def decrypt_file(key, input_file, output_file):
with open(input_file, 'rb') as f:
iv = f.read(16) # 读取初始向量
ciphertext = f.read()
cipher = Cipher(algorithms.AES(key), modes.CFB(iv), backend=default_backend())
decryptor = cipher.decryptor()
with open(output_file, 'wb') as f:
f.write(decryptor.update(ciphertext) + decryptor.finalize())
if __name__ == "__main__":
key = os.urandom(32) # 生成一个随机密钥(32字节用于AES-256)
encrypt_file(key, 'example.txt', 'example.enc') # 加密文件
decrypt_file(key, 'example.enc', 'example_decrypted.txt') # 解密文件