Skip to content

Can't import cryptography generated pkcs12 into macos keychain #7293

Closed
@ojii

Description

@ojii

Versions:

  • Python: 3.10.1
  • cryptography: 37.0.2
  • cffi: 1.15.0

Cryptography installed with poetry 1.2.0b1

I'm trying to create a self-signed certificate with cryptography, which mostly works, but it fails to import to macos (12.1) keychain. If I export the same certificate & private key as a chained PEM file and then use the openssl command line tool to convert it into a p12, I can successfully import it.

This is the code I use to try to export the p12 using cryptography:

def export(path: Path, cert: x509.Certificate, key: rsa.RSAPrivateKeyWithSerialization, password: bytes):
    with path.open('wb') as fobj:
        fobj.write(
            pkcs12.serialize_key_and_certificates(
                name=None,
                cas=None,
                key=key,
                cert=cert,
                encryption_algorithm=serialization.BestAvailableEncryption(password),
            )
        )

However, if instead I do this, macos is happy to import it:

def export(
    path: Path,
    cert: x509.Certificate,
    key: rsa.RSAPrivateKeyWithSerialization,
    password: bytes,
):
    with path.with_suffix(".pem").open("wb") as fobj:
        fobj.write(
            key.private_bytes(
                encoding=serialization.Encoding.PEM,
                format=serialization.PrivateFormat.TraditionalOpenSSL,
                encryption_algorithm=serialization.BestAvailableEncryption(password),
            )
        )
        fobj.write(cert.public_bytes(encoding=serialization.Encoding.PEM))
    subprocess.check_call(
        [
            "openssl",
            "pkc12",
            "-export",
            "-in",
            str(path.with_suffix(".pem")),
            "-passin",
            f"pass:{password.decode()}",
            "-out",
            str(path),
            "-passout",
            f"pass:{password.decode()}",
        ]
    )

Am I using serialize_key_and_certificates wrong?

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions