我使用以下命令生成了私钥和公钥:
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
答案 0 :(得分:6)
如果在Python3上,您还需要以二进制模式打开密钥,例如:
with open('private_key.pem', 'rb') as privatefile:
答案 1 :(得分:4)
Python-RSA使用PEM RSAPublicKey格式,PEM RSAPublicKey格式使用页眉和页脚行: openssl NOTES
-----开始RSA公钥----- ----- END RSA PUBLIC KEY -----
以RSAPublicKey格式输出私钥的公共部分: openssl EXAMPLES
openssl rsa -in key.pem -RSAPublicKey_out -out pubkey.pem
答案 2 :(得分:1)
要使用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)
答案 3 :(得分: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/
答案 4 :(得分: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