Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load a public RSA key into Python-RSA from a file?

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
like image 981
Amine Kerkeni Avatar asked May 10 '13 12:05

Amine Kerkeni


People also ask

How do I import an RSA key?

Importing an RSA Key Container You can use the Aspnet_regiis.exe tool with the –pi switch to import an RSA key container from an XML file. You must also specify whether the imported key container is a machine-level or user-level key container.


2 Answers

To load an OpenSSL generated public key file with python-rsa library, try

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)
like image 140
haiyizxx Avatar answered Oct 22 '22 07:10

haiyizxx


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

with open('private_key.pem', 'rb') as privatefile:
like image 45
Kimvais Avatar answered Oct 22 '22 09:10

Kimvais