如何使用openssl生成的文件在Python-RSA中加载公共RSA密钥?

Ami*_*eni 11 python openssl rsa pem

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

openssl genrsa -out private_key.pem 512
openssl rsa -in private_key.pem -pubout -out public_key.pem
Run Code Online (Sandbox Code Playgroud)

然后我尝试使用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"
Run Code Online (Sandbox Code Playgroud)

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

ValueError: No PEM start marker "-----BEGIN RSA PUBLIC KEY-----" found
Run Code Online (Sandbox Code Playgroud)

Kim*_*ais 7

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

with open('private_key.pem', 'rb') as privatefile:
Run Code Online (Sandbox Code Playgroud)


hai*_*zxx 7

要使用 python-rsa 库加载 OpenSSL 生成的公钥文件,请尝试

with open('public_key.pub', mode='rb') as public_file:
    key_data = public_file.read()
    public_key = rsa.PublicKey.load_pkcs1_openssl_pem(key_data)
Run Code Online (Sandbox Code Playgroud)


小智 6

Python-RSA 使用 PEM RSAPublicKey 格式,PEM RSAPublicKey 格式使用页眉和页脚行: openssl NOTES

-----BEGIN RSA PUBLIC KEY-----
-----END RSA PUBLIC KEY-----
Run Code Online (Sandbox Code Playgroud)

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

 openssl rsa -in key.pem -RSAPublicKey_out -out pubkey.pem
Run Code Online (Sandbox Code Playgroud)