首页 > 解决方案 > Python列表的RSA加密

问题描述

我在逐个元素地加密 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'

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

标签: pythonlistrsa

解决方案


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

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

我不确定 Crypto 版本,但我的方法名称使用 camelCase,尽管在其他示例中使用了 lower_case。

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)

推荐阅读