python“不支持RSA密钥格式";从 .pem 文件读取时 [英] python "RSA key format is not supported" when reading from .pem file

查看:132
本文介绍了python“不支持RSA密钥格式";从 .pem 文件读取时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:

from Crypto.PublicKey import RSA

#Write key to file
key = RSA.generate(4096)
privateKey = key.exportKey()
file1 = open('keyfile.pem', 'wb')
file1.write(privateKey)
file1.close()

#Read key from file
file2 = open('keyfile.pem', 'rb')
key = RSA.importKey(file2.read()) #this is the problem

错误是不支持 RSA 密钥格式".任何人都可以帮助我以最佳方式从文件中写入/读取私钥吗?

The error is "RSA key format is not supported." Can anyone help me with the best way to write/read the private key from a file?

推荐答案

您的代码有多个问题,主要是您读写密钥的方式.您永远不会关闭文件,然后在读取功能期间将其打开两次;尝试将您的代码更改为:

You have multiple issues with your code, mainly the way you are reading and writing the key. You never close the file, then open it twice during your read function; try changing your code to:

#Write key to file
key = RSA.generate(4096)
f = open('keyfile.pem', 'wb')
f.write(key.exportKey('PEM'))
f.close()

#Read key from file
f = open('keyfile.pem', 'rb')
key = RSA.importKey(f.read())

结果:

<_RSAobj @0x10d3cb2d8 n(4096),e,d,p,q,u,private>

这篇关于python“不支持RSA密钥格式";从 .pem 文件读取时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆