You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python RSA加解密程序报错求助:AttributeError问题

RSA加密解密错误排查与修复

错误原因分析

  • 解密器初始化参数错误
    PKCS1_OAEP.new()要求传入RSA密钥对象(如生成的keyPair或导入后的密钥实例),但你传入的privKeyPEM是导出的PEM格式字节串,并非密钥对象。代码尝试访问密钥对象的n属性时,因privKeyPEM是bytes类型无此属性,触发AttributeError。

  • 密文处理方式错误
    encrypted本身就是加密后的bytes对象,你用str(encrypted)会得到带b''前缀的字符串,再通过ast.literal_eval解析属于多余操作,还可能引入编码问题。

修正后的代码

import ast
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
import binascii
 
keyPair = RSA.generate(3072)
 
pubKey = keyPair.publickey()
print(f"Public key:  (n={hex(pubKey.n)}, e={hex(pubKey.e)})")
pubKeyPEM = pubKey.exportKey()
print(pubKeyPEM.decode('utf-8'))
 
print(f"Private key: (n={hex(pubKey.n)}, d={hex(keyPair.d)})")
privKeyPEM = keyPair.exportKey()
print(privKeyPEM.decode('utf-8'))
 
# 加密部分
msg = input("Enter message to encrypt: ")
msg = msg.encode()
encryptor = PKCS1_OAEP.new(pubKey)
encrypted = encryptor.encrypt(msg)
print("Encrypted (ciphertext): ", binascii.hexlify(encrypted))

print("=============")
print("=============")

# 解密部分:使用原始RSA密钥对象创建解密器
decryptor = PKCS1_OAEP.new(keyPair)
# 直接使用加密后的bytes对象解密,无需额外转换
decrypted = decryptor.decrypt(encrypted)
print("Plaintext (decrypted message):")
print(decrypted.decode('utf-8'))  # 转字符串输出更易读

扩展场景:从PEM导入私钥

如果实际场景中私钥是从文件或存储的PEM串读取,可通过以下方式导入密钥对象:

# 从PEM字节串导入私钥
imported_priv_key = RSA.import_key(privKeyPEM)
decryptor = PKCS1_OAEP.new(imported_priv_key)

内容的提问来源于stack exchange,提问作者juan perez

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 10:45:04