Python读取加密文件的全面指南
Python读取加密文件的全面指南
在日常开发中,我们经常需要处理加密文件——无论是配置文件、日志还是用户数据。Python提供了丰富的库来应对各种加密场景。本文将带你从基础到进阶,掌握读取加密文件的核心技巧。
一、加密基础
加密分为对称加密(如AES)和非对称加密(如RSA)。对称加密使用同一密钥加解密,速度快;非对称加密使用公钥/私钥对,更安全但较慢。
二、读取对称加密文件(以AES为例)
假设你有一个用AES-256-CBC加密的文件secret.dat,密钥和IV已知。Python可以使用cryptography库:
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend
import base64
def decrypt_aes_file(filepath, key, iv):
with open(filepath, 'rb') as f:
ciphertext = f.read()
cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=default_backend())
decryptor = cipher.decryptor()
plaintext = decryptor.update(ciphertext) + decryptor.finalize()
# 去除填充(PKCS7)
pad_len = plaintext[-1]
return plaintext[:-pad_len]
# 使用示例
key = base64.b64decode('your-base64-key-here')
iv = base64.b64decode('your-base64-iv-here')
data = decrypt_aes_file('secret.dat', key, iv)
print(data.decode('utf-8'))三、读取非对称加密文件(RSA)
对于使用公钥加密、私钥解密的文件,可以用cryptography如下:
from cryptography.hazmat.primitives import serialization, hashes
from cryptography.hazmat.primitives.asymmetric import padding
def decrypt_rsa_file(filepath, private_key_path, passphrase=None):
with open(private_key_path, 'rb') as key_file:
private_key = serialization.load_pem_private_key(
key_file.read(),
password=passphrase
)
with open(filepath, 'rb') as f:
ciphertext = f.read()
plaintext = private_key.decrypt(
ciphertext,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
)
return plaintext
# 使用示例
decrypted = decrypt_rsa_file('encrypted.dat', 'private_key.pem')
print(decrypted.decode('utf-8'))四、处理哈希校验
有时文件仅经过哈希处理(如SHA256)用于完整性验证,并非加密。读取时需重新计算哈希并与存储值对比:
import hashlib
def verify_file_hash(filepath, expected_hash):
sha256_hash = hashlib.sha256()
with open(filepath, 'rb') as f:
for chunk in iter(lambda: f.read(4096), b''):
sha256_hash.update(chunk)
return sha256_hash.hexdigest() == expected_hash
# 示例
if verify_file_hash('data.txt', 'a1b2c3...'):
print('文件完整')五、最佳实践与注意事项
- 密钥安全:切勿硬编码密钥,使用环境变量或密钥管理服务。
- 错误处理:解密失败时捕获异常(如
InvalidToken)。 - 性能:大文件建议分块处理,避免内存溢出。
- 库选择:
cryptography是推荐库,也可用PyCryptodome。
六、总结
Python读取加密文件并不复杂,关键是选择合适的算法并妥善管理密钥。本文介绍了常见场景的代码,你可以根据具体需求调整。记住,加密是防御的第一道防线,但永远不要忘了备份密钥!