Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get public key using PyOpenSSL?

I'm tring to create python script, that would take PKCS#12 package and print some information contained in x509 certificate and using for this purpouses PyOpenSSL module. So far i want to fetch from certificate public key. But PKey object doesn't have appropriate method. Where can I move out of here ? Any ideas how to get public key ?

pfx=open('./1.p12','rb').read()
PKCS=crypto.load_pkcs12(pfx)
cert=PKCS.get_certificate()
PKey=cert.get_pubkey()

print PKey
<OpenSSL.crypto.PKey object at 0x012432D8>

Thanks.

like image 468
usp Avatar asked Apr 28 '12 11:04

usp


People also ask

How can I get public key from private key?

Get the public key from the private key with ssh-keygen-y This option will read a private OpenSSH format file and print an OpenSSH public key to stdout. -f filename Specifies the filename of the key file.


2 Answers

First you can load the certificate like this

from OpenSSL import crypto

#cert is the encrypted certificate int this format -----BEGIN -----END    
crtObj = crypto.load_certificate(crypto.FILETYPE_PEM, cert)
pubKeyObject = crtObj.get_pubkey()
pubKeyString = crypto.dump_publickey(crypto.FILETYPE_PEM,pubKeyObject)
print pubKeyString

you will see something like

-----BEGIN PUBLIC KEY----- 
....
....
-----END PUBLIC KEY-----
like image 99
CamiloP Avatar answered Sep 19 '22 17:09

CamiloP


I am assuming you want to read the public key from the file.

First install pyopenssl

pip install pyopenssl

from OpenSSL import crypto
import os

   file_path = os.path.join(os.getcwd(),'/certificates/test.crt')
   f = open(file_path, "r")
   cert = f.read()
   pub_key_obj = crypto.load_certificate(crypto.FILETYPE_PEM, cert).get_pubkey()
   pub_key = crypto.dump_publickey(crypto.FILETYPE_PEM,pub_key_obj)
   print(pub_key)

You will get output as:

-----BEGIN PUBLIC KEY-----

....

-----END PUBLIC KEY-----

like image 28
user3785966 Avatar answered Sep 20 '22 17:09

user3785966