MatthiasValvekens / pyHanko

pyHanko: sign and stamp PDF files
MIT License
494 stars 71 forks source link

Pass bytes or BytesIO directly to load_pkcs12 signer #443

Open pawel-steto opened 3 months ago

pawel-steto commented 3 months ago

Thank you for this amazing project!

Due to the way our infrastructure works, we store our certificate files as base64 strings. Currently, we need to create temporary files and pass their paths to the load_pkcs12 function.

Would you be open to a PR that allows the load_pkcs12 function to accept a BytesIO object or the byte content directly?

I am open to any advice on how you would like me to proceed with this contribution.

MatthiasValvekens commented 3 months ago

Sure, why not. The logic to read key material from PEM/DER data evolved similarly in the past, you can model your change off of that.

joneeky commented 3 months ago

You have to make a new method from the Signer.load_pkcs12. Just need to change a little code:

from cryptography.hazmat.primitives.serialization import pkcs12
from pyhanko.keys import _translate_pyca_cryptography_key_to_asn1, _translate_pyca_cryptography_cert_to_asn1
from pyhanko.sign import SimpleSigner
from pyhanko_certvalidator.registry import SimpleCertificateStore

class MySigner(SimpleSigner):
    @classmethod
    def load_pkcs12_from_bytes(
            cls,
            pfx_bytes,
            ca_chain_files=None,
            other_certs=None,
            passphrase=None,
            signature_mechanism=None,
            prefer_pss=False
    ):
        ca_chain = (
            cls._load_ca_chain(ca_chain_files) if ca_chain_files else set()
        )
        if ca_chain is None:  # pragma: nocover
            return None
        try:
            (
                private_key,
                cert,
                other_certs_pkcs12,
            ) = pkcs12.load_key_and_certificates(pfx_bytes, passphrase)
        except (IOError, ValueError, TypeError):
            return None
        kinfo = _translate_pyca_cryptography_key_to_asn1(private_key)
        cert = _translate_pyca_cryptography_cert_to_asn1(cert)
        other_certs_pkcs12 = set(
            map(_translate_pyca_cryptography_cert_to_asn1, other_certs_pkcs12)
        )

        cs = SimpleCertificateStore()
        certs_to_register = ca_chain | other_certs_pkcs12
        if other_certs is not None:
            certs_to_register |= set(other_certs)
        cs.register_multiple(certs_to_register)
        return SimpleSigner(
            signing_key=kinfo,
            signing_cert=cert,
            cert_registry=cs,
            signature_mechanism=signature_mechanism,
            prefer_pss=prefer_pss,
        )