python - 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'
如何使用用户的输入加密列表?请帮忙...
解决方案
加密密钥通常生成一次并以多种格式之一保存到文件中。使用密码进一步保护私钥或将私钥存储在文件系统中的安全位置也很常见。
要使用公钥加密,您通常会从某个外部来源获取密钥,但对于此测试代码,我们使用我们生成的测试密钥。
我不确定 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)
推荐阅读
- asp.net-core - 使用 Windows 身份验证时 PolicyServerClaimsMiddleware 中的 PolicyServer.Local 错误
- python - 对包含文本框的谷歌表单的响应?
- java - 相机未跟踪时无法创建锚点
- python - 使用python自动登录
- algorithm - 处理图中的负循环
- node.js - 使用“表单数据”的邮递员响应正文为空
- python - 在 Docker 上运行的 Django 中的加密错误
- flutter - 扑。如何检查自动续订订阅是否仍然有效
- dictionary - 使用映射函数-Python更新列表内的字典键
- google-cloud-platform - 您如何授予对两个独立 Google Cloud Platform (GCP) 项目资源的访问权限?