【Python练习】053. 编写一个函数,实现简单的文件加密和解密功能
053. 编写一个函数,实现简单的文件加密和解密功能
- 053. 编写一个函数,实现简单的文件加密和解密功能
-
- 安装依赖
- 文件加密和解密代码
-
- 代码说明:
- 示例运行:
- 注意事项:
- 应用场景
- 加密与解密的区别
- 实现方法
-
- 方法1:使用对称加密(如AES)
- 方法2:使用非对称加密(如RSA)
- 选择依据
053. 编写一个函数,实现简单的文件加密和解密功能
以下是一个简单的Python函数,用于实现文件的加密和解密功能。这里使用了对称加密算法(如AES),因为它是实现文件加密的常用方法之一。我们将使用cryptography
库来完成这个任务。
安装依赖
首先,确保安装了cryptography
库。如果尚未安装,可以通过以下命令安装:
pip install cryptography
文件加密和解密代码
以下代码提供了一个简单的文件加密和解密功能:
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import padding
import osdef generate_key(password: str, salt: bytes) -> bytes:"""使用密码和盐值生成密钥:param password: 用户提供的密码:param salt: 盐值:return: 生成的密钥"""kdf = PBKDF2HMAC(algorithm=hashes.SHA256(),length=32, # AES-256需要32字节的密钥salt=salt,iterations=100000,backend=default_backend())return kdf.derive(password.encode())def encrypt_file(input_file: str, output_file: str, password: str):"""加密文件:param input_file: 输入文件路径:param output_file: 输出文件路径:param password: 加密密码"""# 生成随机盐值salt = os.urandom(16)# 生成密钥key = generate_key(password, salt)# 生成随机IV(初始化向量)iv = os.urandom(16)# 创建AES加密器cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=default_backend())encryptor = cipher