Error while encrypting message with RSA python
Use the sample code to encrypt a message using RSA, but I am getting 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 some 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 usage is Windows, what could be related to this issue?
source to share
The error indicates that the method encrypt
does not support encryption of the string message. Try to encode the string in bytes first using encode
for example:
print(RSAPubKey.encrypt("Hello.".encode('utf-8'), 32))
It is also worth noting that according to the documentation it encrypt
does RSA encryption using a "tutorial" which is unstable due to lack of padding. Instead, you should use either Crypto.Cipher.PKCS1_OAEP
or Crypto.Cipher.PKCS1_v1_5
.
source to share