Python中对称加密与非对称加密结合使用的案例

在Python中,结合对称加密和非对称加密可以充分利用两者的优势:对称加密速度快,适合加密大量数据,非对称加密安全性高,适合加密对称密钥。这种组合方式常用于安全通信场景。

典型案例:使用RSA加密AES密钥,然后用AES加密数据

from Crypto.Cipher import AES, PKCS1_OAEP
from Crypto.PublicKey import RSA
from Crypto.Random import get_random_bytes
import base64

# 生成RSA密钥对
rsa_key = RSA.generate(2048)
private_key = rsa_key.export_key()
public_key = rsa_key.publickey().export_key()

# 生成AES对称密钥
aes_key = get_random_bytes(16)  # AES-128,密钥长度16字节

# 用RSA公钥加密AES密钥
rsa_cipher = PKCS1_OAEP.new(RSA.import_key(public_key))
encrypted_aes_key = rsa_cipher.encrypt(aes_key)

# 用AES密钥加密数据
data = b"这是需要加密的大量数据"
aes_cipher = AES.new(aes_key, AES.MODE_EAX)
ciphertext, tag = aes_cipher.encrypt_and_digest(data)

# 解密过程:先用RSA私钥解出AES密钥,再用AES密钥解出数据
rsa_decipher = PKCS1_OAEP.new(RSA.import_key(private_key))
decrypted_aes_key = rsa_decipher.decrypt(encrypted_aes_key)

aes_decipher = AES.new(decrypted_aes_key, AES.MODE_EAX, nonce=aes_cipher.nonce)
decrypted_data = aes_decipher.decrypt_and_verify(ciphertext, tag)

print("解密后的数据:", decrypted_data.decode('utf-8'))

  

posted @ 2025-11-13 15:59  1010阿龙  阅读(10)  评论(0)    收藏  举报