Code: Select all
from lxml import etree
from signxml import XMLSigner, methods
from cryptography.hazmat.primitives.serialization import pkcs12
# Extract PK and Cert
private_key, cert, _ = pkcs12.load_key_and_certificates(pfx_data, cert_password)
# Load XML
xml_str = '''
123456789
'''
root = etree.fromstring(xml_str)
# Configure XMLSigner
signer = XMLSigner(method=methods.enveloped, signature_algorithm="rsa-sha256", digest_algorithm="sha256")
# Sign XML (referencing the ID from the tag EvtPJ)
signed_root = signer.sign(root, key=private_key, cert=[cert], reference_uri="#ID123")
# load batch XML
main_xml_str = '''
'''
main_root = etree.fromstring(main_xml_str)
# Find tag that matches the ID
evento_element = main_root.find(".//{http://www.reinf.esocial.gov.br/schemas/envioLoteEventosAssincrono/v1_00_00}evento[@id='ID123']")
if evento_element is not None:
# Insert signed XML into tag
evento_element.append(signed_root)
else:
print("ID from Element not found")
# Convert the signed xml to formatted string
final_xml = etree.tostring(main_root, pretty_print=False, xml_declaration=False, encoding="utf-8")
# Save the final XML into a file
with open("xml_final.xml", "wb") as file:
file.write(final_xml)
< /code>
Signiertes Batch XML -Ausgang: < /p>
123456789
[...][...][...]