python – NotImplementedError:使用模块Crypto.Cipher.PKCS1_OAEP而不是错误

我正在尝试在Python中进行RSA加密.所以我生成了一个公钥/私钥,使用公钥加密消息并将密文写入文本文件.我使用的代码如下:

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()

但是现在当我运行应用程序时,我收到以下错误:

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

无论我如何尝试实施Crypto.Cipher.PKCS1_OAEP,错误仍然存​​在.我试过导入Crypto.Cipher.PKCS1_OAEP,来自Crypto.Cipher.PKCS1_OAEP导入RSA,来自Crypto.Cipher.PKCS1_OAEP导入随机,来自Crypto.Cipher.PKCS1_OAEP导入ast,导入Crypto.Cipher并没有帮助.

我尝试从Crypto.Cipher.PKCS1_OAEP导入RSA但是然后错误是:

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'

我检查了我的文件,我确实有RSA包.

我该如何纠正这个问题?

解决方法:

您需要使用new创建PKCS1_OAEP的实例,并使用它来加密/解密您的消息.

from Crypto.Cipher import PKCS1_OAEP

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

和解密相同

decryptor = PKCS1_OAEP.new(key)
decrypted = decryptor.decrypt(ast.literal_eval(str(encrypted)))
上一篇:在python中加密 – 在Javascript中解密


下一篇:Asp.Net Core Identity 隐私数据保护