Python文件加密与解密实战指南
Python文件加密与解密实战指南
在数据安全日益重要的今天,文件加密成为保护敏感信息的必备技能。Python凭借其丰富的库生态,让文件加密变得简单高效。本文将带你从零开始,掌握使用Python对文件进行加密和解密的核心方法。
为什么需要文件加密?
无论是个人隐私(如密码本、日记)还是企业数据(如客户资料、财务记录),一旦泄露都可能造成严重后果。加密能将明文转化为密文,即使文件被窃取,没有密钥也无法读取。
对称加密 vs 非对称加密
对称加密:使用同一个密钥加密和解密,速度快,适合大文件。常见算法有AES、ChaCha20等。
非对称加密:使用公钥加密、私钥解密,安全性更高但速度慢,适合小数据或密钥交换。常见算法有RSA、ECC。
实战:使用cryptography库进行AES加密
安装
pip install cryptography生成密钥
from cryptography.fernet import Fernet
key = Fernet.generate_key()
with open('secret.key', 'wb') as key_file:
key_file.write(key)加密文件
from cryptography.fernet import Fernet
def encrypt_file(file_path, key):
cipher = Fernet(key)
with open(file_path, 'rb') as file:
file_data = file.read()
encrypted_data = cipher.encrypt(file_data)
with open(file_path + '.encrypted', 'wb') as file:
file.write(encrypted_data)
print('加密完成!')解密文件
def decrypt_file(encrypted_path, key):
cipher = Fernet(key)
with open(encrypted_path, 'rb') as file:
encrypted_data = file.read()
decrypted_data = cipher.decrypt(encrypted_data)
with open(encrypted_path.replace('.encrypted', '_decrypted'), 'wb') as file:
file.write(decrypted_data)
print('解密完成!')进阶:使用PyCryptodome实现AES-CBC模式
对于更大或更敏感的文件,推荐使用AES-CBC模式,它需要初始化向量(IV)来增加安全性。
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
import os
def encrypt_file_aes_cbc(file_path, key):
iv = os.urandom(16)
cipher = AES.new(key, AES.MODE_CBC, iv)
with open(file_path, 'rb') as f:
plaintext = f.read()
ciphertext = cipher.encrypt(pad(plaintext, AES.block_size))
with open(file_path + '.enc', 'wb') as f:
f.write(iv + ciphertext)
def decrypt_file_aes_cbc(encrypted_path, key):
with open(encrypted_path, 'rb') as f:
iv = f.read(16)
ciphertext = f.read()
cipher = AES.new(key, AES.MODE_CBC, iv)
plaintext = unpad(cipher.decrypt(ciphertext), AES.block_size)
with open(encrypted_path.replace('.enc', '_decrypted'), 'wb') as f:
f.write(plaintext)非对称加密:RSA加密小型文件
如果需要安全分发密钥,可以使用RSA。但注意RSA只能加密小块数据(如256字节),通常用于加密对称密钥。
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
def generate_rsa_keys():
key = RSA.generate(2048)
private_key = key.export_key()
public_key = key.publickey().export_key()
with open('private.pem', 'wb') as f:
f.write(private_key)
with open('public.pem', 'wb') as f:
f.write(public_key)
def rsa_encrypt_file(file_path, public_key_path):
with open(public_key_path, 'rb') as f:
public_key = RSA.import_key(f.read())
cipher = PKCS1_OAEP.new(public_key)
with open(file_path, 'rb') as f:
data = f.read()
encrypted_data = cipher.encrypt(data)
with open(file_path + '.rsa', 'wb') as f:
f.write(encrypted_data)最佳实践
- 密钥管理:密钥文件本身也要加密存储,或使用硬件安全模块(HSM)。
- 备份密钥:一旦丢失密钥,数据永久无法恢复。
- 选择算法:对于常规需求,推荐AES-256-GCM(认证加密)。
- 文件完整性:同时使用HMAC或GCM模式防止篡改。
总结
Python提供了多种方式实现文件加密解密,从简单的Fernet到灵活的AES-CBC,再到RSA密钥交换。根据实际场景选择合适的方案,让你的文件安全无忧。动手试试上面的代码吧!