Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decode text encoded with RSA

I have a RSA public/private key pair and passphrase. I am trying to decode text encrypted using using above key(s). The encoded text is always 512 chars long alpha-num string.

I have tried using the code provided at SOF question Decrypt using an RSA public key with PyCrypto

First I used my private key which was encoded with AES-256-CBC from a PEM file. This is start of privkey.pem which made me think its AES-256 encrypted

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

but I received following error message.

ValueError: PEM encryption format not supported.

So I asked the source for a private key without AES encryption which they gave me. Now using this key the decrypted works and the decrypted text looks like below (I am only showing some of the text)

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

This is not my plain text. What am I doing wrong? can someone help me to decode this text.

EDIT 1:

Based on Maarten's answer below, I have tried the following code but I am still getting errors.

Here is my code for decryption

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)))

and I get error:

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

Note that I had to convert my private key from PEM to DER using the code below becasue using PEM file I was getting SyntaxError: unexpected EOF while parsing

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

becasue

like image 429
Khurram Majeed Avatar asked May 13 '26 18:05

Khurram Majeed


1 Answers

Here is the solution that I have found.

First of all I am using pycryptodome library instead of pycrypto.

These are my encode and decode functions:

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

Using above two functions I was able to encode/decode the data correctly.

like image 172
Khurram Majeed Avatar answered May 15 '26 07:05

Khurram Majeed



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!