0

I am dealing with this issue for some days and I don't get it. I have googled and tried several solutions indicated here, but without success. I want to encrypt a message (string) with a public key generated with openssl.

I am generating the keys with these commands:

# Private key:
openssl genrsa -out private_key.pem 2048

# Public key:
openssl rsa -in private_key.pem -outform PEM -pubout -out public_key.pem 

What I want to accomplish is to open the public key and encrypt the data with this snippet:

from Crypto.PublicKey import RSA

# Open RSA file
with open("public_key.pem", "r") as fk:
    rsa_key = RSA.importKey(fk.read())

message_encrypted = rsa_key.encrypt("Hello.", <X>)

I do not understand what do I have to write at <X>. But when I write some integer value, it fails with this error:

self = <Crypto.PublicKey._slowmath._RSAKey object at 0x7fcb153de748>, m = 'HELLO'

    def _encrypt(self, m):
        # compute m**d (mod n)
>       return pow(m, self.e, self.n)
E       TypeError: unsupported operand type(s) for pow(): 'str', 'int', 'int'

Best regards!

11
  • Are you using Pycrypto or Pycryptodome? Because in Pycrypto, K is ignored (ref) and in Pycryptodome .encrypt() raises a NotImplementedError exception. So, with Pycrypto you should be able to use the method with any int as K, and with Pycryptodome you shouldn't be able to use the method at all. Commented Sep 4, 2019 at 18:38
  • 1
    From the traceback it seems ._encrypt() is called at some point. The method expects m to be a number, but in this case it is a string, so in order to use it you should convert the message to a number. However this method performs raw encryption and it would be best to avoid it and use OAEP instead. Commented Sep 4, 2019 at 18:58
  • @t.m.adam, I do not intend to use that parameter, that why I do not know what to write at <X>. Commented Sep 4, 2019 at 19:50
  • You can have any string or int as <X>, it is ignored eitherway. It is the m parameter (the message) that causes the exception. Commented Sep 4, 2019 at 19:55
  • Are you telling me it is a library's problem? Commented Sep 4, 2019 at 21:02

1 Answer 1

1

Thanks to the comments I was able to resolve this problem, not exactly with the class have I asked, but using another equivalent explained in this site.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.