解码使用 RSA 编码的文本

Decode text encoded with RSA

我有一个 RSA public/private 密钥对和密码。我正在尝试解码使用上述密钥加密的文本。编码文本始终为 512 个字符长的字母数字字符串。

我已经尝试使用 SOF 问题 Decrypt using an RSA public key with PyCrypto

中提供的代码

首先,我使用了我的私钥,它是用 PEM 文件中的 AES-256-CBC 编码的。 这是 privkey.pem 的开始,这让我觉得它的 AES-256 已加密

-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: AES-256-CBC
<rest of the data>
-----END RSA PRIVATE KEY-----

但我收到了以下错误消息。

ValueError: PEM encryption format not supported.

所以我向消息来源询问了他们给我的没有 AES 加密的私钥。现在使用这个密钥解密后的作品和解密后的文本如下所示(我只展示了一些文本)

b'\x93\n(\x92\x02\x9aF*?\x18"\x19\x12Gn\xc2\<rest of the text>'

这不是我的纯文本。我究竟做错了什么?谁能帮我解码这段文字。

编辑 1:

根据下面 Maarten 的回答,我尝试了以下代码,但仍然出现错误。

这是我的解密代码

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

encrypted_text = "39085fc25e<HIDDEN>2fcce845760391ff"

key = RSA.importKey(open("\path_to_key\private.der", encoding="utf8").read())
cipher = PKCS1_OAEP.new(key)

message = cipher.decrypt(ast.literal_eval(str(uid)))

我得到错误:

UnicodeDecodeError: 'utf-8' codec can't decode byte 0x82 in position 1: invalid start byte

请注意,我必须使用下面的代码将我的私钥从 PEM 转换为 DER,因为我使用 PEM 文件得到 SyntaxError: unexpected EOF while parsing

openssl rsa -in private_key.pem -out private_key.der -outform DER

因为

这是我找到的解决方案。

首先我使用 pycryptodome librray 而不是 pycrypto。

下面是我的编码和解码函数。

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

def encode_rsa(message, key_path):    
    key = RSA.importKey(open(key_path).read())
    cipher = PKCS1_OAEP.new(key)
    ciphertext = cipher.encrypt(message)
    return ciphertext

def decode_rsa(ciphertext, key_path):
    key = RSA.importKey(open(key_path).read())
    cipher = PKCS1_OAEP.new(key)
    # before decrypt convert the hex string to byte_array 
    message = cipher.decrypt(bytearray.fromhex(ciphertext))
    return message

使用以上两个函数,我能够 encode/deode 正确地获取数据。