生成RSA并写入文件

问题描述 投票:0回答:1

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

[*]创建密钥时出错

[*]创建密钥时出错

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。

python rsa pycrypto hashlib
1个回答
1
投票

你应该捕获异常并显示知道问题,但我认为你的问题是write方法,private_key是它的字节,但是你必须通过str来编写方法,你可以尝试:

   keyfile.write(private_key.decode())

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

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)

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

© www.soinside.com 2019 - 2024. All rights reserved.