openssl - 如何在 python RSA中加载由openssl生成的文件中的public RSA密钥?

  显示原文与译文双语对照的内容

我生成了一个 private 和一个 public 键,其中包含以下命令:


openssl genrsa -out private_key.pem 512


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



然后,我尝试使用 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"



当 python 脚本试图加载 public 密钥时,它将失败:


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



时间: 原作者:

python rsa使用 rtc RSAPublicKey格式,并且 rtc RSAPublicKey格式使用页眉和页脚行: openssl NOTES

-----BEGIN RSA public KEY-----------END RSA public KEY------

以RSAPublicKey格式输出 private 键的public 部分: openssl示例


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



如果在Python3上,你还需要以二进制模式打开密钥,e.g:


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



原作者:
...