AttributeError: 'bytes' 对象没有属性 'n'

时间:2021-05-25 14:12:11

标签: python rsa pycryptodome

我正在尝试使用 Crypto 方法对一段文本进行编码。

我需要用给定的公钥使用RSA方法对一段字符串进行编码,这是我目前编写的代码,参考this link.

我的代码...

from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
import base64

def encrypt_private_key(a_message, private_key):
    encryptor = PKCS1_OAEP.new(private_key)
    encrypted_msg = encryptor.encrypt(a_message)
    encoded_encrypted_msg = base64.b64encode(encrypted_msg)
    return encoded_encrypted_msg


key = open('public.pem', 'r')
byte_key = bytes(key.read().encode())
byte_message = b'1200|2000.00'

output = encrypt_private_key(byte_message, byte_key)
print(byte_message)

但是,当我尝试运行此代码时,会出现此错误。

File "C:\Users\Acer\Desktop\Web Development\Learning new features\Play video on scroll\venv\lib\site-packages\Crypto\Cipher\PKCS1_OAEP.py", line 107, in encrypt
    modBits = Crypto.Util.number.size(self._key.n)
AttributeError: 'bytes' object has no attribute 'n'

我不明白我到底做错了什么......

非常感谢任何帮助。 谢谢!

1 个答案:

答案 0 :(得分:1)

加密使用接收者的公钥,因此只有接收者才能用他们的私钥解密密文。相比之下,签名使用签名者的私钥,从而使用关联的公钥执行验证。在给定的情况下,要对消息进行加密,因此要应用收件人的公钥。

在贴出的代码中,缺少带 RSA.import_key() 的密钥的导入,从而导致错误。如果添加,则加密成功:

from Crypto.Cipher import PKCS1_OAEP
from Crypto.PublicKey import RSA
import base64

def encrypt_with_public_key(a_message, public_key):
    encryptor = PKCS1_OAEP.new(public_key)
    encrypted_msg = encryptor.encrypt(a_message)
    encoded_encrypted_msg = base64.b64encode(encrypted_msg)
    return encoded_encrypted_msg

x509pem = """-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAunF5aDa6HCfLMMI/MZLT
5hDk304CU+ypFMFiBjowQdUMQKYHZ+fklB7GpLxCatxYJ/hZ7rjfHH3Klq20/Y1E
bYDRopyTSfkrTzPzwsX4Ur/l25CtdQldhHCTMgwf/Ev/buBNobfzdZE+Dhdv5lQw
KtjI43lDKvAi5kEet2TFwfJcJrBiRJeEcLfVgWTXGRQn7gngWKykUu5rS83eAU1x
H9FLojQfyia89/EykiOO7/3UWwd+MATZ9HLjSx2/Lf3g2jr81eifEmYDlri/OZp4
OhZu+0Bo1LXloCTe+vmIQ2YCX7EatUOuyQMt2Vwx4uV+d/A3DP6PtMGBKpF8St4i
GwIDAQAB
-----END PUBLIC KEY-----"""
# x509pem = open('public.pem', 'r').read() # load the key alternatively from the file system

key = RSA.import_key(x509pem)      # add the key import with import_key() or importKey()
byte_message = b'1200|2000.00'

encoded_encrypted_msg = encrypt_with_public_key(byte_message, key)
print(encoded_encrypted_msg.decode('utf-8'))

s。也this example 在带有 OAEPadding 的 RSA 的 PyCryptodome 文档中。