Answer a question

How do/can I generate a PKCS#12 file using python and the cryptography module?

It's pretty easy using said module to generate the contents of .pem file for a private key:

keyPEMBytes = privateKey.private_bytes(
    encoding=serialization.Encoding.PEM,
    format=serialization.PrivateFormat.TraditionalOpenSSL,
    encryption_algorithm=serialization.NoEncryption())

Also easy to generate the contents of a .cer/.pem file for an associated cert:

certBytes = certificate.public_bytes(encoding=serialization.Encoding.PEM)

But I need them (and their chain) balled up on a single .p12 (PKCS12 file). Said module documents how to parse/consume PKCS12 formats, but nothing (that I can find) about how one can generate them.

My understanding of PKI stuff is hit and miss though, so maybe I'm just not searching the right keyword in the documentation?

I can create the .p12 file at the command line on Linux using

openssl pkcs12 -export -out myIdentity.p12 -inkey myPrivKey.pem -in myCert.crt -certfile myCertChain.crt

So I could just wrap calls like this with subprocess/cmd and mess with tempfiles/pipes. I was hoping to keep it all in memory/python though.

Is there a different python TLS library that I should be considering, that can do this?

Answers

As you noted, cryptography can parse PKCS12 (at least the subset used by 99.99% of people) with load_key_and_certificates, but serialization to PKCS12 is not currently supported.

I'm one of the core developers for the project and in general cryptography's feature set is driven by users filing issues that explain their use case and need for a particular feature. I'd recommend writing something up on the tracker for discussion. It sounds like your needs would be covered by a simple API looking roughly like:

from cryptography.hazmat.primitives.serialization.pkcs12 import generate_pkcs12

pem_pkcs12 = generate_pkcs12(
    BestAvailableEncryption(b"somepassword"), 
    key, 
    [cert1, cert2]
)

Update: this feature is implemented in pyca/cryptography 3.0:

https://cryptography.io/en/latest/hazmat/primitives/asymmetric/serialization.html?highlight=pkcs12#cryptography.hazmat.primitives.serialization.pkcs12.serialize_key_and_certificates

Logo

Python社区为您提供最前沿的新闻资讯和知识内容

更多推荐