Khurram Majeed - 3 months ago 25

Python Question

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.

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

Answer

Here is the solution that I have found.

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

Below are my encode and decode functions.

```
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/deode the data correctly.