Search code examples
python-3.xpkcs#12python-cryptography

pkcs12 extract cert and key from pfx file


I'm trying to extract the cert and key from the pfx file, and then write them to the x.key and x.crt files. I can get the cert and key by the below Python code, my question is how to write them to the file.

private_key, certificate, additional_certificates = pkcs12.load_key_and_certificates(pxfile.read(), None)

the certificate type is x509.Certificate, how can I convert it to string to write to the file?


Solution

  • get bytes via the blow code, then open file with "wb" to write.

    certificate_bytes = certificate.public_bytes(Encoding.PEM)
    private_key_bytes = private_key.private_bytes(Encoding.PEM, PrivateFormat.PKCS8, NoEncryption())