作者:alive | 来源:互联网 | 2023-02-01 19:01
我正在尝试在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
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
,from Crypto.Cipher.PKCS1_OAEP import RSA
,from Crypto.Cipher.PKCS1_OAEP import Random
,from Crypto.Cipher.PKCS1_OAEP import ast
,和import Crypto.Cipher
,没有这些帮助的.
我试过from Crypto.Cipher.PKCS1_OAEP import RSA
但是错误是:
Traceback (most recent call last):
File "C:/Users/RedCode/PycharmProjects/AdvancedApps/Encryption/RSA Example.py", line 3, in
from Crypto.Cipher.PKCS1_OAEP import RSA
ImportError: cannot import name 'RSA'
我检查了我的文件,我确实有RSA包.
我该如何纠正这个问题?
1> Pelle..:
您需要使用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)))