Python列表的RSA加密

2024-04-28 07:52:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我对一个Python列表元素一个元素地加密感到很麻烦。每个元素都是一个字符串。该列表是一个字符串。这是我的密码:

from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP

#### Generate the public and private keys ####
key = RSA.generate(1024, e=65537)
priv_key = key.exportKey("PEM")
public_key = key.publickey().exportKey("PEM")


#Let's get some information!!
firstName = input("Enter your First Name: ") 
lastName = input("Enter your Last Name: ") 
id = input("Enter your Personal ID: ") 

#list = [first_name, last_name, id]
list = ['Bob', 'Dylan', '15898']
listEncrypted = []

#Now let's encrypt the list with a public key
list_length = len(list)

for index in range(list_length-1):
    cipher = PKCS1_OAEP.new(public_key)
    ciphertext = cipher.encrypt(list[index])
    listEncrypted.append(ciphertext)

我得到的错误是:

  File "C:\Users\moo\.spyder-py3\RSA.py", line 122, in <module>
  ciphertext = cipher.encrypt(list[index])

  File "C:\Users\moo\anaconda3\lib\site-packages\Crypto\Cipher\PKCS1_OAEP.py", line 107, in encrypt
  modBits = Crypto.Util.number.size(self._key.n)

  AttributeError: 'bytes' object has no attribute 'n'

如何使用用户的输入对列表进行加密?请帮忙


Tags: keyin元素列表inputyourindexpublic
1条回答
网友
1楼 · 发布于 2024-04-28 07:52:51

加密密钥通常生成一次,并以多种格式之一保存到文件中。私钥通常还需要使用密码进一步保护或存储在文件系统中的安全位置

要使用公钥加密,您通常会从一些外部源获取密钥,但对于此测试代码,我们使用生成的测试密钥

我不确定加密版本,但我的方法名称使用camelCase,尽管在其他示例中使用小写

from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP

#### Generate the public and private keys for test ####
key = RSA.generate(1024, e=65537)
priv_key = key.exportKey("PEM")
public_key = key.publickey().exportKey("PEM")

text = "This is secret"

#Now let's encrypt the list with a public key
key = RSA.importKey(public_key)
cipher = PKCS1_OAEP.new(key)
ciphertext = cipher.encrypt(text.encode("utf-8"))
print(text, ciphertext)

相关问题 更多 >