Python文件加密实战:保护敏感数据的高级技术

引言

在数字化时代,数据安全至关重要。Python作为一门强大的编程语言,提供了丰富的加密库来实现文件加密。本文将带你了解如何利用Python对文件进行加密,确保敏感信息不被泄露。

加密基础

加密分为对称加密和非对称加密。对称加密使用相同的密钥进行加解密,速度快,适合大文件;非对称加密使用公钥/私钥对,安全性更高,但速度较慢。常见对称算法有AES,非对称有RSA。

Python加密库

Python标准库中cryptographypycryptodome是常用的加密库。推荐使用cryptography,因为它更现代且安全。

pip install cryptography

对称加密:AES文件加密

AES(高级加密标准)是目前最流行的对称加密算法。以下是一个使用cryptography库进行AES加密和解密的示例:

from cryptography.fernet import Fernet

def generate_key():
    return Fernet.generate_key()

def encrypt_file(key, input_file, output_file):
    fernet = Fernet(key)
    with open(input_file, 'rb') as f:
        data = f.read()
    encrypted = fernet.encrypt(data)
    with open(output_file, 'wb') as f:
        f.write(encrypted)

def decrypt_file(key, input_file, output_file):
    fernet = Fernet(key)
    with open(input_file, 'rb') as f:
        encrypted_data = f.read()
    decrypted = fernet.decrypt(encrypted_data)
    with open(output_file, 'wb') as f:
        f.write(decrypted)

注意:Fernet基于AES-128 CBC模式,并提供了认证加密,确保数据完整性。

非对称加密:RSA文件加密

对于需要交换密钥的场景,RSA更合适。通常使用RSA加密一个对称密钥,然后再用对称密钥加密文件。

from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import rsa, padding
from cryptography.hazmat.primitives import serialization

def generate_rsa_keys():
    private_key = rsa.generate_private_key(
        public_exponent=65537,
        key_size=2048,
    )
    public_key = private_key.public_key()
    return private_key, public_key

def encrypt_file_rsa(public_key, input_file, output_file):
    # 首先生成对称密钥
    from cryptography.fernet import Fernet
    symmetric_key = Fernet.generate_key()
    # 加密对称密钥
    encrypted_key = public_key.encrypt(
        symmetric_key,
        padding.OAEP(
            mgf=padding.MGF1(algorithm=hashes.SHA256()),
            algorithm=hashes.SHA256(),
            label=None
        )
    )
    # 加密文件内容
    fernet = Fernet(symmetric_key)
    with open(input_file, 'rb') as f:
        data = f.read()
    encrypted_data = fernet.encrypt(data)
    # 保存:加密后的密钥 + 加密后的数据
    with open(output_file, 'wb') as f:
        f.write(len(encrypted_key).to_bytes(4, byteorder='big'))
        f.write(encrypted_key)
        f.write(encrypted_data)

def decrypt_file_rsa(private_key, input_file, output_file):
    from cryptography.fernet import Fernet
    with open(input_file, 'rb') as f:
        key_len = int.from_bytes(f.read(4), byteorder='big')
        encrypted_key = f.read(key_len)
        encrypted_data = f.read()
    # 解密对称密钥
    symmetric_key = private_key.decrypt(
        encrypted_key,
        padding.OAEP(
            mgf=padding.MGF1(algorithm=hashes.SHA256()),
            algorithm=hashes.SHA256(),
            label=None
        )
    )
    # 解密文件
    fernet = Fernet(symmetric_key)
    decrypted_data = fernet.decrypt(encrypted_data)
    with open(output_file, 'wb') as f:
        f.write(decrypted_data)

安全实践

  • 密钥管理:密钥必须安全存储,可使用环境变量或密钥管理系统。
  • 使用认证加密:推荐AEAD模式,如AES-GCM,防止篡改。
  • 清理内存:敏感数据用完后及时覆盖。
  • 避免硬编码:密钥不应写在代码中。

总结

Python提供了强大的加密工具,通过合理选择算法和库,可以高效地加密文件。对称加密适合单用户场景,非对称加密适用于多用户密钥分发。始终遵循安全最佳实践,才能有效保护数据。

希望本文能帮助你在项目中实现安全的文件加密。如有疑问,欢迎交流!