7

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.

usp
  • 111
  • 1
  • 1
  • 4
  • Wait, it looks like you're already using the `get_pubkey` method to get the public key. What's not working? – larsks Apr 28 '12 at 11:22
  • it appears you are using `pyOpenSSL` and it appears you are not accepting answer relating to the use of `dump_privatekey` which is working for RSA public keys without any additional parameters. Givent he porrly described question I can only derive that you are trying to ask about viewing any/all key types not knowing in advance the cipher or passphrase - which is simply not possible. You either know what you want to generate by giving hte appropriate inputs, or you naively guess or brute force the result you are looking for - sorry to say but it is the truth – Stof Oct 05 '21 at 23:52

4 Answers4

7

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-----
CamiloP
  • 132
  • 1
  • 4
2

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')
with open(file_path, "r") as f:
    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)

or

file_path = '~/.ssh/private_key'
with open(file_path, "rb") as f:
    raw = f.read()
private_key_obj = crypto.load_privatekey(crypto.FILETYPE_PEM, raw)
pub_key = crypto.dump_publickey(crypto.FILETYPE_PEM, private_key_obj)
print(pub_key)

You will get output as:

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

....

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

Javier Buzzi
  • 6,296
  • 36
  • 50
user3785966
  • 2,578
  • 26
  • 18
-3

Would this work?

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

from OpenSSL import crypto

crypto.dump_privatekey(PKey)
abc
  • 123
  • 1
  • 6
-3

Instead use:

c.dump_privatekey(c.FILETYPE_TEXT,pubkey)
jww
  • 97,681
  • 90
  • 411
  • 885
Abhisheietk
  • 160
  • 5