【问题标题】:Generating RSA and writing to file生成 RSA 并写入文件
【发布时间】:2023-04-03 11:30:02
【问题描述】:

为什么我在这段代码中得到异常: 我得到输出:

[*] 创建密钥时出错

[*] 创建密钥时出错

import os, hashlib
from Crypto.Cipher import AES
from Crypto.PublicKey import RSA

raw_key = RSA.generate(2048)
private_key = raw_key.exportKey('PEM')
try:
with open('master_private.pem', 'w+') as keyfile:
    keyfile.write(private_key)
    keyfile.close()
print ("[*] Successfully created your MASTER RSA private key")
except:
print ("[*] Error creating your key")

make_public = raw_key.publickey()
public_key = make_public.exportKey('PEM')
try:
with open("master_public.pem", "w+") as keyfile:
    keyfile.write(public_key)
    keyfile.close()
print ("[*] Successfully created your MASTER RSA public key")
except:
print ("[*] Error creating your key")

文件已成功创建,但未填充任何内容。我刚刚开始使用 Python。

【问题讨论】:

  • 您确定public_keyprivate_key 包含数据? print(len(public_key))
  • 要么删除 try except 块,要么捕获程序使用 except Exception as e 返回的异常。然后打印e
  • @RiteshAgrawal print (e) 显示write() argument must be str, not bytes

标签: python rsa pycrypto hashlib


【解决方案1】:

您应该捕获异常并显示以了解问题,但我认为您的问题是 write 方法,private_key 它的字节但您必须传递一个 str 来写入方法,您可以尝试:

   keyfile.write(private_key.decode())

其他问题可能是您的权限权限,可能没有创建文件的权限,尝试捕获标题并打印以了解发生了什么

try:
    with open('master_private.pem', 'w+') as keyfile:
    keyfile.write(private_key)
    keyfile.close()
    print ("[*] Successfully created your MASTER RSA private key")
except Exception as e:
    print ("[*] Error creating your key", e)

还要检查你的语法为什么该代码没有很好地尝试

【讨论】:

  • 谢谢,需要解码。 write() argument must be str, not bytes
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-13
  • 1970-01-01
  • 2018-12-12
  • 2017-05-11
  • 1970-01-01
  • 2013-09-26
相关资源
最近更新 更多