I am trying to RSA encryption in Python. So I have a public/private key being generated, encrypting the message using the public key and writing the ciphertext to a text file. The code I am using is as follows:
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 implementing Crypto.Cipher.PKCS1_OAEP
, the error persists. I have tried 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 those helped.
I tried from Crypto.Cipher.PKCS1_OAEP import RSA
but then the error was:
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 do have the RSA package.
How can I correct this issue?
You need to create an instance of PKCS1_OAEP using new, and use that 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)))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With