pyca / pyopenssl

A Python wrapper around the OpenSSL library
https://pyopenssl.org/
Apache License 2.0
882 stars 421 forks source link

Loading Multiple Keys from a hierarchical PKI P12 #770

Open SlackWyrm opened 6 years ago

SlackWyrm commented 6 years ago

Hi there, I have been scouring the internet to find a solution to this and have come up empty handed. I am playing around with PKI and Certificates and am using PyOpenSSL to parse and extract the Keys from the P12 file issued.

Now under normal circumstances this would easily be achieved with the following command:

p12File = crypto.load(pkcs12(open(p12CertFile,'rb').read(),password)
Cert = p12.get_certificate()

privKey = p12File.get_privateKey()
pubKey = Cert.get_publicKey()

The problem I have run into is that the P12 file I have generated has its Certs revoked forcing it to create a new Key Pair. When I use the following OpenSSL command line I can see all the different Private Keys in there.

openssl pkcs12 -in p12CertFile -nocerts -nodes -password pass:SuperSecretPassword

And the output goes something like:

<Bag Information>
-----BEGIN PRIVATE KEY-----
....
-----END PRIVATE KEY-----

<Bag Information>
-----BEGIN PRIVATE KEY-----
....
-----END PRIVATE KEY-----

<Bag Information>
-----BEGIN PRIVATE KEY-----
....
-----END PRIVATE KEY-----

<Bag Information>
-----BEGIN PRIVATE KEY-----
....
-----END PRIVATE KEY-----

Now when I try to do the same with the PyOpenSSL I am only given the FIRST (Public and Private) Key. I tried to use

Cert = p12.get_ca_certificates()

and I can see all the Certificates issued including different public keys but I can only still retrieve the first Private Key corresponding to the first Public Key. The rest of the Private Keys are not retrievable through PyOpenSSL's published API.

Is there any way of extracting the rest of the Private Keys from the P12 file using PyOpenSSL? Or any other alternatives? Thanks.

reaperhulk commented 6 years ago

Unfortunately pyOpenSSL's PKCS12 support is not very good and doesn't support what you want (an iterable to get everything out of the PKCS12 bag). I'm not sure what alternatives are out there, as unfortunately pyca/cryptography doesn't currently expose a PKCS12 implementation.

SlackWyrm commented 6 years ago

Thanks Paul for your quick heads up. Would you happen to know if there are any soon to immediate plans to implement such feature? or should I be thinking a complete redesign of my assignment?

reaperhulk commented 6 years ago

We would accept a PR here to expand support (without breaking current API). We'd also be happy to discuss it over on cryptography, but to my knowledge no one is actively working on this. Volunteer projects 😞