15

I generated a private and a public key using OpenSSL 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:

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:

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

5 回答 5

12

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

with open('private_key.pem', 'rb') as privatefile:
于 2014-04-01T08:44:57.300 回答
6

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

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

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

 openssl rsa -in key.pem -RSAPublicKey_out -out pubkey.pem
于 2014-02-17T12:40:45.987 回答
3

要使用 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)
于 2019-02-06T15:24:36.503 回答
0
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.backends import default_backend


def load_keys():
    with open("public.pem", "rb") as f:
        public = serialization.load_pem_public_key(
            f.read(), backend=default_backend()
        )
    with open("private.pem", "rb") as f:
        private = serialization.load_pem_private_key(
            f.read(), None, backend=default_backend()
        )
    return private, public
于 2019-11-14T13:54:14.267 回答
0

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

ssh-keygen -t rsa

并生成这样的公钥:

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

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

于 2017-12-27T06:57:02.903 回答