python_signed_mail/functions/load_p12_smime.py

41 lines
1.3 KiB
Python

from cryptography.hazmat.primitives.serialization import (
pkcs12,
Encoding,
PrivateFormat,
NoEncryption,
)
from cryptography.hazmat.backends import default_backend
from asn1crypto.keys import PrivateKeyInfo # type: ignore
from asn1crypto import x509 # type: ignore
def load_p12_smime(config_dict: dict):
try:
with open(config_dict["p12_file"], "rb") as f:
p12_data = f.read()
# Load the P12 data
private_key, certificate, _ = pkcs12.load_key_and_certificates(
data=p12_data,
password=config_dict["p12_password"].encode(),
backend=default_backend(),
)
# Convert the private key to PKCS#8 format (ASN.1)
private_key_bytes = private_key.private_bytes( # type: ignore
encoding=Encoding.DER,
format=PrivateFormat.PKCS8,
encryption_algorithm=NoEncryption(),
)
# Parse the private key using asn1crypto
private_key_info = PrivateKeyInfo.load(private_key_bytes)
# Convert the certificate to ASN.1 format using asn1crypto
cert_bytes = certificate.public_bytes(Encoding.DER) # type: ignore
asn1_cert = x509.Certificate.load(cert_bytes)
return private_key_info, asn1_cert
except Exception as e:
raise ValueError(f"Error loading P12 file: {e}")