Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error with encrypt message with RSA python

Use the sample code to encrypt a message using the RSA, but I get the following error.

Traceback (most recent call last):
  File "E:/PythonProjects/skypy/skypy/codebase/utils/crypto.py", line 32, in <module>
    print(RSAPubKey.encrypt("Hello.", 32))
  File "E:\Programs\Python3.4\lib\site-packages\Crypto\PublicKey\RSA.py", line 150, in encrypt
    return pubkey.pubkey.encrypt(self, plaintext, K)
  File "E:\Programs\Python3.4\lib\site-packages\Crypto\PublicKey\pubkey.py", line 75, in encrypt
    ciphertext=self._encrypt(plaintext, K)
  File "E:\Programs\Python3.4\lib\site-packages\Crypto\PublicKey\RSA.py", line 224, in _encrypt
    return (self.key._encrypt(c),)
  File "E:\Programs\Python3.4\lib\site-packages\Crypto\PublicKey\_slowmath.py", line 65, in _encrypt
    return pow(m, self.e, self.n)
TypeError: unsupported operand type(s) for pow(): 'str', 'int', 'int'

Here is sample code

from Crypto.PublicKey import RSA
from Crypto.Util import randpool

blah = randpool.RandomPool()
RSAKey = RSA.generate(1024, blah.get_bytes)

RSAPubKey = RSAKey.publickey()
print(RSAPubKey.encrypt("Hello.", 32))

OS use is Windows, of what may be due to this problem ?

like image 523
Krasimir Avatar asked May 28 '15 16:05

Krasimir


1 Answers

The error suggests that the encrypt method does not support encrypting a string message. Try encoding your string to bytes first using encode, e.g.:

print(RSAPubKey.encrypt("Hello.".encode('utf-8'), 32))

It's also worth noting that, per the documentation, encrypt performs "textbook" RSA encryption, which is insecure due to the lack of padding. You should instead look to use either Crypto.Cipher.PKCS1_OAEP or Crypto.Cipher.PKCS1_v1_5.

like image 143
Iridium Avatar answered Nov 01 '22 02:11

Iridium