Created
February 25, 2017 19:36
-
-
Save osvalr/223fe203675df0eb31baa60b19ab95d0 to your computer and use it in GitHub Desktop.
Sign XML file in python with a x509 certificate
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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
sample.xml