如何在Python-RSA中加載openssl生成的文件中的公共RSA密鑰?


Answers

如果在Python3上,還需要以二進制模式打開密鑰,例如:

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

我使用以下命令生成了私鑰和公鑰:

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

然後我嘗試使用Python-RSA加載一個python腳本:

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腳本嘗試加載公鑰時失敗:

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