首页 > 解决方案 > 解密 RSA 会话密钥的正确方法

问题描述

我正在使用 pycryptodomex 进行 RSA 加密、解密。 我关注这篇文章

from Cryptodome.PublicKey import RSA
from Cryptodome.Cipher import AES, PKCS1_OAEP

file_in = open("encrypted_data.bin", "rb")

private_key = RSA.import_key(open("private.pem").read())

enc_session_key, nonce, tag, ciphertext = \
   [ file_in.read(x) for x in (private_key.size_in_bytes(), 16, 16, -1) ]

# Decrypt the session key with the public RSA key
cipher_rsa = PKCS1_OAEP.new(private_key)
session_key = cipher_rsa.decrypt(enc_session_key)

# Decrypt the data with the AES session key
cipher_aes = AES.new(session_key, AES.MODE_EAX, nonce)
data = cipher.decrypt_and_verify(ciphertext, tag)

它显示以下错误

ValueError Traceback (most recent call last) in 11 # 用公钥解密会话密钥 12 cipher_rsa = PKCS1_OAEP.new(private_key) ---> 13 session_key = cipher_rsa.decrypt(enc_session_key) 14 15 # 用公钥解密数据AES 会话密钥

C:\ProgramData\Anaconda3\lib\site-packages\Cryptodome\Cipher\PKCS1_OAEP.py in decrypt(self, ciphertext) 165 # Step 1b and 1c 166 if len(ciphertext) != k or k 167 raise ValueError("Ciphertext长度不正确。") 168 # 步骤 2a (O2SIP) 169 ct_int = bytes_to_long(ciphertext)

ValueError:长度不正确的密文。

代码有什么问题吗?

标签: pythonencryptionrsapycryptopycryptodome

解决方案


推荐阅读