NotImplementedError: use Crypto.Cipher.PKCS1_OAEP module instead of error

I am trying to encrypt RSA in Python. This way I generate a public / private key by encrypting the message using the public key and writing the encrypted text to a text file. The code I'm using looks like this:

from Crypto.PublicKey import RSA
from Crypto import Random
import ast

random_generator = Random.new().read
key = RSA.generate(1024, random_generator)  

publickey = key.publickey()  

encrypted = publickey.encrypt('encrypt this message', 32)

print('encrypted message:', encrypted)
f = open('encryption.txt', 'w')
f.write(str(encrypted))
f.close()

f = open('encryption.txt', 'r')
message = f.read()

decrypted = key.decrypt(ast.literal_eval(str(encrypted)))

print('decrypted', decrypted)

f = open('encryption.txt', 'w')
f.write(str(message))
f.write(str(decrypted))
f.close()

      

But now when I run the application I get the following error:

Traceback (most recent call last):
  File "C:/Users/RedCode/PycharmProjects/AdvancedApps/Encryption/RSA Example.py", line 10, in <module>
    encrypted = publickey.encrypt('encrypt this message', 32)
  File "C:\Users\RedCode\AppData\Local\Programs\Python\Python36-32\lib\site-packages\Crypto\PublicKey\RSA.py", line 390, in encrypt
    raise NotImplementedError("Use module Crypto.Cipher.PKCS1_OAEP instead")
NotImplementedError: Use module Crypto.Cipher.PKCS1_OAEP instead

      

No matter how I try to execute Crypto.Cipher.PKCS1_OAEP

, the error persists. I tried to import Crypto.Cipher.PKCS1_OAEP

, from Crypto.Cipher.PKCS1_OAEP import RSA

, from Crypto.Cipher.PKCS1_OAEP import Random

, from Crypto.Cipher.PKCS1_OAEP import ast

and import Crypto.Cipher

, and none of them helped.

I tried from Crypto.Cipher.PKCS1_OAEP import RSA

but then there was an error:

Traceback (most recent call last):
  File "C:/Users/RedCode/PycharmProjects/AdvancedApps/Encryption/RSA Example.py", line 3, in <module>
    from Crypto.Cipher.PKCS1_OAEP import RSA
ImportError: cannot import name 'RSA'

      

I checked my files and I have an RSA package.

How can I fix this problem?

+3


source to share


1 answer


You need to instantiate PKCS1_OAEP with a new one and use it to encrypt / decrypt your message.

from Crypto.Cipher import PKCS1_OAEP

encryptor = PKCS1_OAEP.new(publickey)
encrypted = encryptor.encrypt(b'encrypt this message')

      



and the same for decryption

decryptor = PKCS1_OAEP.new(key)
decrypted = decryptor.decrypt(ast.literal_eval(str(encrypted)))

      

+5


source







All Articles