Skip to content

Instantly share code, notes, and snippets.

@ieski
Forked from osvalr/x509_sign.py
Created May 4, 2024 20:12
Show Gist options
  • Save ieski/c147073ac0a3ad41c078d63beec121fc to your computer and use it in GitHub Desktop.
Save ieski/c147073ac0a3ad41c078d63beec121fc to your computer and use it in GitHub Desktop.
Sign XML file in python with a x509 certificate
# coding: utf-8
from lxml import etree
from signxml import xmldsig
cert = open('cert.pem').read()
key = open('key.pem').read()
doc = etree.parse('sample.xml').getroot()
root = etree.fromstring(
etree.tostring(doc),
parser=etree.XMLParser(encoding='ISO-8859-1'))
signed_root = xmldsig(root,
digest_algorithm='sha1').sign(algorithm='rsa-sha1',
key=key,
cert=cert)
signed_root.xpath(
'//ext:UBLExtensions/ext:UBLExtension/ext:ExtensionContent/ds:Signature',
namespaces={
'ext': 'urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2',
'ds': 'http://www.w3.org/2000/09/xmldsig#'
})[0].attrib['Id'] = 'SignSUNAT'
doc = etree.tostring(signed_root, encoding='ISO-8859-1')
with open('result.xml', 'w') as f:
f.write(etree.tostring(signed_root, xml_declaration=True, encoding="ISO-8859-1", pretty_print=True))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment