【问题标题】:How to save and load rsa keys如何保存和加载 rsa 密钥
【发布时间】:2021-11-30 15:46:05
【问题描述】:

我正在尝试加密一些文本,然后将密文和密钥保存在单独的文件中,然后使用“密钥”(json 中的密钥)解密“文件”文件(密文)

我的代码分解

  1. 创建密钥
  2. 打开密钥文件
  3. 将密钥转换为 json
  4. 保存文件
  5. 从用户那里获取文本
  6. 加密
  7. 将密文写入文件
  8. 加载密钥
  9. 获取 e、n、d、p、q 值并分配它们
  10. 从文件中打开和读取密文
  11. 描述和输出

所有代码都有效,除非我尝试从我的 json 文件中分配键,
我明白了:

Traceback (most recent call last):
  File "C:\Users\user\Desktop\python projects\encrption\test.py", line 48, in <module>
    text = rsa.decrypt(cyphertext, loadkedkeys[1]).decode()
  File "C:\Users\user\Desktop\python projects\encrption\.venv\lib\site-packages\rsa\pkcs1.py", line 249, in decrypt
    decrypted = priv_key.blinded_decrypt(encrypted)
TypeError: blinded_decrypt() missing 1 required positional argument: 'encrypted'

我的代码:

import rsa
import json

#make keys
print("new keys")
loadkedkeys = rsa.newkeys(256)
print("file")
#turn keys into json
keysfile = open(file=("kes"), mode="w")
keys = {"keys": []}
keys["keys"].append(((loadkedkeys[0].e), (loadkedkeys[0].n)))
keys["keys"].append(
    (((loadkedkeys[1].e), loadkedkeys[1].n, (loadkedkeys[1].d), (loadkedkeys[1].p), 
(loadkedkeys[1].q))))
keysfile.write(str(json.dumps(keys)))
keysfile.close()

text = input("message: ")
#encrypt
cyphertext = rsa.encrypt(text.encode(), loadkedkeys[0])

keysFile = open(file="kes", mode="r")
keysfilecontents = keysFile.read()
try:
    keys = json.loads(keysfilecontents)
except:
    print("json error")

loadkedkeys = (rsa.key.PublicKey, rsa.key.PrivateKey)
# setting public key
loadkedkeys[0].e = keys["keys"][0][0]
loadkedkeys[0].n = keys["keys"][0][1]
# setting private key
loadkedkeys[1].e = keys["keys"][1][0]
loadkedkeys[1].n = keys["keys"][1][1]
loadkedkeys[1].d = keys["keys"][1][2]
loadkedkeys[1].p = keys["keys"][1][3]
loadkedkeys[1].q = keys["keys"][1][4]
keysFile.close()

print(loadkedkeys[0])
print(loadkedkeys[1])

open("text.txt", "wb").write(cyphertext)

text = open("text.txt", "rb").read()

text = rsa.decrypt(cyphertext, loadkedkeys[1]).decode()

print(text)

【问题讨论】:

    标签: python json encryption rsa


    【解决方案1】:

    所以我似乎已经想通了,我改变了,所以我通过 rsa.PublicKey(value,value) 分配值,还交换了 e 和 n 值

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-07
      • 1970-01-01
      • 2017-06-22
      • 1970-01-01
      • 2010-12-17
      • 1970-01-01
      相关资源
      最近更新 更多