Python 文本加密实战:从基础到进阶

引言

在数字化时代,数据安全至关重要。Python作为一门强大的编程语言,提供了丰富的库来帮助开发者实现文本加密。本文将带你从基础到进阶,掌握使用Python对文本进行加密的核心技术。

1. 对称加密:AES

AES(高级加密标准)是目前最常用的对称加密算法。使用pycryptodome库可以轻松实现。

from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes

key = get_random_bytes(16)  # 16字节密钥
cipher = AES.new(key, AES.MODE_EAX)
text = b'Hello World'
ciphertext, tag = cipher.encrypt_and_digest(text)

# 解密
cipher_dec = AES.new(key, AES.MODE_EAX, cipher.nonce)
plaintext = cipher_dec.decrypt_and_verify(ciphertext, tag)
print(plaintext.decode())

注意:密钥必须保密,nonce(一次性数字)需随密文一起传输。

2. 非对称加密:RSA

RSA使用公钥加密、私钥解密,适用于密钥分发场景。使用cryptography库实现。

from cryptography.hazmat.primitives import 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()

# 加密
message = b'Secret text'
ciphertext = public_key.encrypt(message, padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None))

# 解密
plaintext = private_key.decrypt(ciphertext, padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None))
print(plaintext.decode())

RSA加密速度慢,适合加密小数据,通常用于加密对称密钥。

3. 哈希与Base64

哈希函数(如SHA-256)不可逆,常用于密码存储。Base64则用于编码二进制数据为文本。

import hashlib
import base64

text = 'Hello'
hash_obj = hashlib.sha256(text.encode())
hex_dig = hash_obj.hexdigest()
print('SHA256:', hex_dig)

# Base64编码
encoded = base64.b64encode(text.encode())
print('Base64:', encoded.decode())

注意:哈希不是加密,而是单向摘要。

4. 完整示例:混合加密

实际应用中常结合对称与非对称加密:用RSA加密AES密钥,再使用AES加密文本。

# 生成AES密钥和RSA密钥对
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
from cryptography.hazmat.primitives.asymmetric import rsa, padding
from cryptography.hazmat.primitives import hashes

rsa_private_key = rsa.generate_private_key(65537, 2048)
rsa_public_key = rsa_private_key.public_key()
aes_key = get_random_bytes(16)

# 使用公钥加密AES密钥
encrypted_aes_key = rsa_public_key.encrypt(aes_key, padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None))

# 使用AES加密文本
cipher_aes = AES.new(aes_key, AES.MODE_EAX)
text = b'Confidential data'
ciphertext, tag = cipher_aes.encrypt_and_digest(text)
nonce = cipher_aes.nonce

# 传输:encrypted_aes_key + nonce + tag + ciphertext

# 解密
# 私钥解密AES密钥
aes_key_dec = rsa_private_key.decrypt(encrypted_aes_key, padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None))
cipher_dec = AES.new(aes_key_dec, AES.MODE_EAX, nonce)
plaintext = cipher_dec.decrypt_and_verify(ciphertext, tag)
print(plaintext.decode())

总结

Python提供了多种方式对文本进行加密。选择合适的加密算法取决于你的需求:对称加密速度快,适合大量数据;非对称加密安全但慢;哈希用于完整性验证。务必妥善保管密钥,并遵循安全最佳实践。