如何从openssl生成的文件中加载Python-RSA公钥?

时间:2021-03-30 18:29:43

I generated a private and a public key with the following commands:

我生成了一个私钥和公钥,包含以下命令:

openssl genrsa -out private_key.pem 512
openssl rsa -in private_key.pem -pubout -out public_key.pem

I then tried to load them with a python script using Python-RSA:

然后我尝试用python - rsa脚本加载它们:

import os
import rsa

with open('private_key.pem') as privatefile:
    keydata = privatefile.read()
privkey = rsa.PrivateKey.load_pkcs1(keydata,'PEM')

with open('public_key.pem') as publicfile:
    pkeydata = publicfile.read()

pubkey = rsa.PublicKey.load_pkcs1(pkeydata)

random_text = os.urandom(8)

#Generate signature
signature = rsa.sign(random_text, privkey, 'MD5')
print signature

#Verify token
try:
    rsa.verify(random_text, signature, pubkey)
except:
    print "Verification failed"

My python script fails when it tries to load the public key:

我的python脚本在尝试加载公钥时失败:

ValueError: No PEM start marker "-----BEGIN RSA PUBLIC KEY-----" found

3 个解决方案

#1


4  

Python-RSA uses the PEM RSAPublicKey format and the PEM RSAPublicKey format uses the header and footer lines: openssl NOTES

Python-RSA使用PEM RSAPublicKey格式,PEM RSAPublicKey格式使用header和footer行:openssl NOTES

-----BEGIN RSA PUBLIC KEY----- -----END RSA PUBLIC KEY-----

- - - - - - - - - - - - - - - -端开始RSA公钥RSA公钥- - - - - -

Output the public part of a private key in RSAPublicKey format: openssl EXAMPLES

以RSAPublicKey格式输出私钥的公共部分:openssl示例

 openssl rsa -in key.pem -RSAPublicKey_out -out pubkey.pem

#2


6  

If on Python3, You also need to open the key in binary mode, e.g:

如果在Python3上,你还需要在二进制模式下打开密钥,例如:

with open('private_key.pem', 'rb') as privatefile:

#3


0  

You can generate private key by ssh-keygen:

您可以通过ssh-keygen生成私钥:

ssh-keygen -t rsa

and generate public key like this:

并生成这样的公钥:

ssh-keygen -e -m pem -f xxx > pubkey.pem

http://blog.oddbit.com/2011/05/08/converting-openssh-public-keys/

http://blog.oddbit.com/2011/05/08/converting-openssh-public-keys/

#1


4  

Python-RSA uses the PEM RSAPublicKey format and the PEM RSAPublicKey format uses the header and footer lines: openssl NOTES

Python-RSA使用PEM RSAPublicKey格式,PEM RSAPublicKey格式使用header和footer行:openssl NOTES

-----BEGIN RSA PUBLIC KEY----- -----END RSA PUBLIC KEY-----

- - - - - - - - - - - - - - - -端开始RSA公钥RSA公钥- - - - - -

Output the public part of a private key in RSAPublicKey format: openssl EXAMPLES

以RSAPublicKey格式输出私钥的公共部分:openssl示例

 openssl rsa -in key.pem -RSAPublicKey_out -out pubkey.pem

#2


6  

If on Python3, You also need to open the key in binary mode, e.g:

如果在Python3上,你还需要在二进制模式下打开密钥,例如:

with open('private_key.pem', 'rb') as privatefile:

#3


0  

You can generate private key by ssh-keygen:

您可以通过ssh-keygen生成私钥:

ssh-keygen -t rsa

and generate public key like this:

并生成这样的公钥:

ssh-keygen -e -m pem -f xxx > pubkey.pem

http://blog.oddbit.com/2011/05/08/converting-openssh-public-keys/

http://blog.oddbit.com/2011/05/08/converting-openssh-public-keys/