Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/292.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/apache-spark/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 生成RSA并写入文件_Python_Rsa_Pycrypto_Hashlib - Fatal编程技术网

Python 生成RSA并写入文件

Python 生成RSA并写入文件,python,rsa,pycrypto,hashlib,Python,Rsa,Pycrypto,Hashlib,为什么在此代码中出现异常: 我得到输出: [*]创建密钥时出错 [*]创建密钥时出错 文件已成功创建,但未填充任何内容。我刚刚开始使用Python。您应该捕获exeception并显示以了解问题所在,但我认为您的问题在于写入方法,为其字节设置私钥,但必须传递str才能写入方法。您可以尝试: keyfile.writeprivate\u key.decode 另一个问题可能是您的权限,可能您没有创建文件的权限,请尝试捕获例外并打印以了解发生了什么 尝试: 打开“master_private.pem

为什么在此代码中出现异常: 我得到输出:

[*]创建密钥时出错

[*]创建密钥时出错


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

您应该捕获exeception并显示以了解问题所在,但我认为您的问题在于写入方法,为其字节设置私钥,但必须传递str才能写入方法。您可以尝试:

keyfile.writeprivate\u key.decode 另一个问题可能是您的权限,可能您没有创建文件的权限,请尝试捕获例外并打印以了解发生了什么

尝试: 打开“master_private.pem”、“w+”作为密钥文件: keyfile.writeprivate\u密钥 keyfile.close 打印[*]已成功创建您的主RSA私钥 例外情况除外,如e: 打印[*]创建密钥时出错,e
还要检查您的语法,为什么该代码没有得到很好的验证

并且您确定公钥和私钥包含数据?printlenpublic_键删除try-exception块或捕获程序使用exception作为e返回的异常。然后print e.@RiteshAgrawal print e告诉我write参数必须是str,而不是bytest谢谢,它需要解码。写入参数必须是str,而不是bytes
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")