Python 加密文件:安全存储与传输的实用指南
Python 加密文件:安全存储与传输的实用指南
在数字化时代,文件安全至关重要。Python 提供了强大的加密库,使我们能够轻松地对文件进行加密和解密。本文将从基础到实战,带你掌握 Python 文件加密的核心技术与最佳实践。
为什么需要文件加密?
无论是个人隐私、商业机密还是敏感数据,在存储或传输时都可能面临泄露风险。文件加密可以确保即使他人获取了文件,也无法读取其内容。Python 作为通用编程语言,拥有丰富的加密工具,能够满足不同场景的需求。
常见加密算法与库
- 对称加密:使用相同的密钥加密和解密。代表算法:AES、DES、3DES。推荐使用 AES(高级加密标准),安全性高且速度快。
- 非对称加密:使用公钥加密、私钥解密。代表算法:RSA、ECC。适合密钥分发场景,但速度较慢,通常用于加密对称密钥。
- 哈希函数:不可逆,用于校验文件完整性。常见算法:SHA-256、MD5(不再安全)。
Python 中常用的加密库:
cryptography:现代、安全、易用,官方推荐。pycryptodome:功能全面,支持多种算法。hashlib:内置库,用于哈希计算。
实战:使用 cryptography 库加密文件
首先安装 cryptography:
pip install cryptography
以下示例演示如何用 AES 对称加密一个文件:
from cryptography.fernet import Fernet
# 生成密钥
key = Fernet.generate_key()
with open('secret.key', 'wb') as key_file:
key_file.write(key)
# 加密文件
cipher = Fernet(key)
with open('data.txt', 'rb') as file:
file_data = file.read()
encrypted_data = cipher.encrypt(file_data)
with open('data.encrypted', 'wb') as file:
file.write(encrypted_data)
print("文件已加密保存为 data.encrypted")
解密时,只需读取密钥并调用 decrypt:
from cryptography.fernet import Fernet
# 读取密钥
with open('secret.key', 'rb') as key_file:
key = key_file.read()
cipher = Fernet(key)
with open('data.encrypted', 'rb') as file:
encrypted_data = file.read()
decrypted_data = cipher.decrypt(encrypted_data)
with open('data.txt', 'wb') as file:
file.write(decrypted_data)
print("文件已解密恢复为 data.txt")
进阶:使用 RSA 非对称加密
非对称加密适用于需要在不同方之间安全传输密钥的场景。使用 cryptography 的 RSA 示例:
from cryptography.hazmat.primitives import serialization, hashes
from cryptography.hazmat.primitives.asymmetric import rsa, padding
# 生成密钥对
private_key = rsa.generate_private_key(
public_exponent=65537,
key_size=2048
)
public_key = private_key.public_key()
# 保存私钥和公钥
with open('private.pem', 'wb') as f:
f.write(private_key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.PKCS8,
encryption_algorithm=serialization.NoEncryption()
))
with open('public.pem', 'wb') as f:
f.write(public_key.public_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PublicFormat.SubjectPublicKeyInfo
))
# 加密数据(注意 RSA 只能加密小块数据,通常结合对称加密使用)
message = b"This is a secret message."
encrypted = public_key.encrypt(
message,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
)
with open('encrypted.bin', 'wb') as f:
f.write(encrypted)
# 解密
with open('encrypted.bin', 'rb') as f:
encrypted_data = f.read()
original_message = private_key.decrypt(
encrypted_data,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
)
print(original_message.decode())
最佳实践与小贴士
- 密钥管理:不要硬编码密钥,使用环境变量或密钥管理服务。
- 安全存储:加密后的文件与密钥分开存放。
- 混合加密:对于大文件,使用对称加密 + 非对称加密交换会话密钥。
- 完整性校验:结合 HMAC 或数字签名防止篡改。
- 性能考虑:根据文件大小选择合适的算法和模式(如 AES-GCM 自带认证)。
总结
Python 让文件加密变得简单而强大。通过选择正确的算法和库,你可以有效保护敏感数据。建议从 cryptography 库开始,深入理解其 API,并根据实际需求调整方案。加密不是万能的,但不加密是万万不能的。