Ejemplo n.º 1
0
    def test_create_2(self):
        root = parse_xml('data/free-sample.xml')
        signature = xmlsig.template.create(
            xmlsig.constants.TransformInclC14N,
            xmlsig.constants.TransformRsaSha1,
            "Signature"
        )
        ref = xmlsig.template.add_reference(
            signature, xmlsig.constants.TransformSha1, uri="", name="R1"
        )
        xmlsig.template.add_transform(ref, xmlsig.constants.TransformEnveloped)
        xmlsig.template.add_reference(
            signature, xmlsig.constants.TransformSha1, uri="#KI", name="RKI"
        )
        ki = xmlsig.template.ensure_key_info(signature, name='KI')
        data = xmlsig.template.add_x509_data(ki)
        xmlsig.template.x509_data_add_certificate(data)
        serial = xmlsig.template.x509_data_add_issuer_serial(data)
        xmlsig.template.x509_issuer_serial_add_issuer_name(serial)
        xmlsig.template.x509_issuer_serial_add_serial_number(serial)
        xmlsig.template.add_key_value(ki)
        qualifying = template.create_qualifying_properties(signature)
        utils.ensure_id(qualifying)
        utils.ensure_id(qualifying)
        props = template.create_signed_properties(
            qualifying, datetime=datetime.now()
        )
        template.add_claimed_role(props, "Supp")
        signed_do = template.ensure_signed_data_object_properties(props)
        template.add_data_object_format(
            signed_do,
            "#R1",
            identifier=ObjectIdentifier("Idenfitier0", "Description")
        )
        template.add_commitment_type_indication(
            signed_do,
            ObjectIdentifier("Idenfitier0", "Description"),
            qualifiers_type=["Tipo"]
        )

        template.add_commitment_type_indication(
            signed_do,
            ObjectIdentifier("Idenfitier1", references=["#R1"]),
            references=["#R1"]
        )
        template.add_data_object_format(
            signed_do,
            "#RKI",
            description="Desc",
            mime_type="application/xml",
            encoding='UTF-8'
        )
        root.append(signature)
        ctx = XAdESContext(ImpliedPolicy(xmlsig.constants.TransformSha1))
        with open(path.join(BASE_DIR, "data/keyStore.p12"), "rb") as key_file:
            ctx.load_pkcs12(crypto.load_pkcs12(key_file.read()))
        with patch('xades.policy.urllib.urlopen') as mock:
            mock.return_value = UrllibMock()
            ctx.sign(signature)
            ctx.verify(signature)
Ejemplo n.º 2
0
 def test_create(self):
     root = parse_xml("data/free-sample.xml")
     signature = xmlsig.template.create(
         xmlsig.constants.TransformInclC14N,
         xmlsig.constants.TransformRsaSha1,
         "Signature",
     )
     signature_id = utils.get_unique_id()
     ref = xmlsig.template.add_reference(signature,
                                         xmlsig.constants.TransformSha1,
                                         uri="",
                                         name="REF")
     xmlsig.template.add_transform(ref, xmlsig.constants.TransformEnveloped)
     xmlsig.template.add_reference(signature,
                                   xmlsig.constants.TransformSha1,
                                   uri="#KI")
     xmlsig.template.add_reference(signature,
                                   xmlsig.constants.TransformSha1,
                                   uri="#" + signature_id)
     ki = xmlsig.template.ensure_key_info(signature, name="KI")
     data = xmlsig.template.add_x509_data(ki)
     xmlsig.template.x509_data_add_certificate(data)
     serial = xmlsig.template.x509_data_add_issuer_serial(data)
     xmlsig.template.x509_issuer_serial_add_issuer_name(serial)
     xmlsig.template.x509_issuer_serial_add_serial_number(serial)
     xmlsig.template.add_key_value(ki)
     qualifying = template.create_qualifying_properties(
         signature, name=utils.get_unique_id())
     props = template.create_signed_properties(qualifying,
                                               name=signature_id)
     template.add_claimed_role(props, "Supp2")
     template.add_production_place(props, city="Madrid")
     template.add_production_place(props,
                                   state="BCN",
                                   postal_code="08000",
                                   country="ES")
     template.add_claimed_role(props, "Supp")
     policy = GenericPolicyId(
         "http://www.facturae.es/politica_de_firma_formato_facturae/"
         "politica_de_firma_formato_facturae_v3_1.pdf",
         u"Politica de Firma FacturaE v3.1",
         xmlsig.constants.TransformSha1,
     )
     root.append(signature)
     with open(path.join(BASE_DIR, "data/keyStore.p12"), "rb") as key_file:
         certificate = crypto.load_pkcs12(key_file.read())
     with open(path.join(BASE_DIR, "data/keyStore2.p12"), "rb") as key_file:
         certificate2 = crypto.load_pkcs12(key_file.read())
     ctx = XAdESContext(
         policy,
         [
             certificate2.get_certificate().to_cryptography(),
             certificate.get_certificate().to_cryptography(),
         ],
     )
     ctx.load_pkcs12(certificate)
     with patch("xades.policy.urllib.urlopen") as mock:
         mock.return_value = UrllibMock()
         ctx.sign(signature)
         ctx.verify(signature)
Ejemplo n.º 3
0
 def test_create(self):
     root = parse_xml('data/free-sample.xml')
     signature = xmlsig.template.create(xmlsig.constants.TransformInclC14N,
                                        xmlsig.constants.TransformRsaSha1,
                                        "Signature")
     signature_id = utils.get_unique_id()
     ref = xmlsig.template.add_reference(signature,
                                         xmlsig.constants.TransformSha1,
                                         uri="",
                                         name="REF")
     xmlsig.template.add_transform(ref, xmlsig.constants.TransformEnveloped)
     xmlsig.template.add_reference(signature,
                                   xmlsig.constants.TransformSha1,
                                   uri="#KI")
     xmlsig.template.add_reference(signature,
                                   xmlsig.constants.TransformSha1,
                                   uri="#" + signature_id)
     ki = xmlsig.template.ensure_key_info(signature, name='KI')
     data = xmlsig.template.add_x509_data(ki)
     xmlsig.template.x509_data_add_certificate(data)
     serial = xmlsig.template.x509_data_add_issuer_serial(data)
     xmlsig.template.x509_issuer_serial_add_issuer_name(serial)
     xmlsig.template.x509_issuer_serial_add_serial_number(serial)
     xmlsig.template.add_key_value(ki)
     qualifying = template.create_qualifying_properties(
         signature, name=utils.get_unique_id())
     props = template.create_signed_properties(qualifying,
                                               name=signature_id)
     template.add_claimed_role(props, "Supp2")
     template.add_production_place(props, city='Madrid')
     template.add_production_place(props,
                                   state='BCN',
                                   postal_code='08000',
                                   country='ES')
     template.add_claimed_role(props, "Supp")
     policy = GenericPolicyId(
         'http://www.facturae.es/politica_de_firma_formato_facturae/'
         'politica_de_firma_formato_facturae_v3_1.pdf',
         u"Politica de Firma FacturaE v3.1", xmlsig.constants.TransformSha1)
     root.append(signature)
     ctx = XAdESContext(policy)
     with open(path.join(BASE_DIR, "data/keyStore.p12"), "rb") as key_file:
         ctx.load_pkcs12(crypto.load_pkcs12(key_file.read()))
     ctx.sign(signature)
     ctx.verify(signature)
Ejemplo n.º 4
0
 def test_create(self):
     root = parse_xml('data/free-sample.xml')
     signature = xmlsig.template.create(xmlsig.constants.TransformInclC14N,
                                        xmlsig.constants.TransformRsaSha1,
                                        "Signature")
     ref = xmlsig.template.add_reference(signature,
                                         xmlsig.constants.TransformSha1,
                                         uri="")
     xmlsig.template.add_transform(ref, xmlsig.constants.TransformEnveloped)
     xmlsig.template.add_reference(signature,
                                   xmlsig.constants.TransformSha1,
                                   uri="#KI")
     xmlsig.template.add_reference(signature,
                                   xmlsig.constants.TransformSha1,
                                   uri="#SIGN")
     ki = xmlsig.template.ensure_key_info(signature, name='KI')
     data = xmlsig.template.add_x509_data(ki)
     xmlsig.template.x509_data_add_certificate(data)
     xmlsig.template.add_key_value(ki)
     qualifying = template.create_qualifying_properties(signature)
     props = template.create_signed_properties(qualifying, name="SIGN")
     template.add_claimed_role(props, "Supp2")
     template.add_production_place(props, 'Madrid')
     template.add_production_place(props, 'BCN', 'BCN', '08000', 'ES')
     template.add_claimed_role(props, "Supp")
     policy = PolicyId()
     policy.id = 'http://www.facturae.es/politica_de_firma_formato_' \
                 'facturae/politica_de_firma_formato_facturae_v3_1.pdf'
     policy.name = u"Politica de Firma FacturaE v3.1"
     policy.hash_method = xmlsig.constants.TransformSha1
     root.append(signature)
     ctx = XAdESContext(policy)
     with open(path.join(BASE_DIR, "data/keyStore.p12"), "rb") as key_file:
         ctx.load_pkcs12(crypto.load_pkcs12(key_file.read()))
     ctx.sign(signature)
     ctx.verify(signature)
Ejemplo n.º 5
0
def get_xml_with_signature(
        xml_without_signature,
        signature_policy_url,
        signature_policy_description,
        certificate_file,
        certificate_password):
    ##https://github.com/etobella/python-xades/blob/master/test/base.py
    #base_path = path.dirname(path.dirname(__file__))
    #root = etree.parse(path.join(base_path, name)).getroot()
    #https://lxml.de/tutorial.html
    parser = etree.XMLParser(remove_blank_text=True)
    root = etree.fromstring(xml_without_signature.encode("utf-8"),parser=parser)
    #https://github.com/etobella/python-xades/blob/master/test/test_xades.py
    signature_id = "xmldsig-{}".format(uuid4())
    signature = xmlsig.template.create(
        xmlsig.constants.TransformInclC14N,
        xmlsig.constants.TransformRsaSha512,
        signature_id)
    ref = xmlsig.template.add_reference(
        signature,
        xmlsig.constants.TransformSha512,
        uri="",
        name=signature_id + "-ref0")
    xmlsig.template.add_transform(
        ref,
        xmlsig.constants.TransformEnveloped)
    xmlsig.template.add_reference(
        signature,
        xmlsig.constants.TransformSha512,
        uri="#" + signature_id + "-keyinfo")
    xmlsig.template.add_reference(
        signature,
        xmlsig.constants.TransformSha512,
        uri="#" + signature_id + "-signedprops",
        uri_type="http://uri.etsi.org/01903#SignedProperties")
    ki = xmlsig.template.ensure_key_info(
        signature,
        name=signature_id + "-keyinfo")
    data = xmlsig.template.add_x509_data(ki)
    xmlsig.template.x509_data_add_certificate(data)
    serial = xmlsig.template.x509_data_add_issuer_serial(data)
    xmlsig.template.x509_issuer_serial_add_issuer_name(serial)
    xmlsig.template.x509_issuer_serial_add_serial_number(serial)
    xmlsig.template.add_key_value(ki)
    qualifying = template.create_qualifying_properties(signature)
    props = template.create_signed_properties(
        qualifying,
        name=signature_id + "-signedprops")
    template.add_claimed_role(props, "supplier")
    policy = GenericPolicyId(
        signature_policy_url,
        signature_policy_description,
        xmlsig.constants.TransformSha512)
    root.append(signature)
    ctx = XAdESContext(policy)
    ctx.load_pkcs12(get_pkcs12(certificate_file, certificate_password))
    #with patch("xades.policy.urllib.urlopen") as mock:
    #    mock.return_value = b64decode(signature_policy_file).read()
    ctx.sign(signature)
    #ctx.verify(signature)

    #Se debe firmar en un paso anterior, y luego remover el signature para
    #ubicarlo en posicion necesaria
    root.remove(signature)
    ext = "urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2"
    ds = "http://www.w3.org/2000/09/xmldsig#"
    position = 0

    #https://lxml.de/tutorial.html
    for element in root.iter("{%s}ExtensionContent" % ext):
        if position == 1:
            element.append(signature)
        position += 1

    #Complememto para añadir atributo faltante
    for element in root.iter("{%s}SignatureValue" % ds):
        element.attrib['Id'] = signature_id + "-sigvalue"



    #https://www.decalage.info/en/python/lxml-c14n
    output = BytesIO()
    root.getroottree().write_c14n(output)#, exclusive=1, with_comments=0
    root = output.getvalue()
    #_logger.info(root)
    return root
Ejemplo n.º 6
0
def get_xml_with_signature(xml_without_signature, signature_policy_url,
                           signature_policy_description, certificate_file,
                           certificate_password):
    ##https://github.com/etobella/python-xades/blob/master/test/base.py
    #base_path = path.dirname(path.dirname(__file__))
    #root = etree.parse(path.join(base_path, name)).getroot()
    #https://lxml.de/tutorial.html
    root = etree.fromstring(xml_without_signature.encode('UTF-8'))
    #https://github.com/etobella/python-xades/blob/master/test/test_xades.py
    signature_id = "xmldsig-{}".format(uuid4())
    signature = xmlsig.template.create(xmlsig.constants.TransformInclC14N,
                                       xmlsig.constants.TransformRsaSha512,
                                       signature_id)
    ref = xmlsig.template.add_reference(signature,
                                        xmlsig.constants.TransformSha512,
                                        uri="",
                                        name=signature_id + "-ref0")
    xmlsig.template.add_transform(ref, xmlsig.constants.TransformEnveloped)
    xmlsig.template.add_reference(signature,
                                  xmlsig.constants.TransformSha512,
                                  uri="#" + signature_id + "-keyinfo")
    xmlsig.template.add_reference(
        signature,
        xmlsig.constants.TransformSha512,
        uri="#" + signature_id + "-signedprops",
        uri_type="http://uri.etsi.org/01903#SignedProperties")
    ki = xmlsig.template.ensure_key_info(signature,
                                         name=signature_id + "-keyinfo")
    data = xmlsig.template.add_x509_data(ki)
    xmlsig.template.x509_data_add_certificate(data)
    serial = xmlsig.template.x509_data_add_issuer_serial(data)
    xmlsig.template.x509_issuer_serial_add_issuer_name(serial)
    xmlsig.template.x509_issuer_serial_add_serial_number(serial)
    xmlsig.template.add_key_value(ki)
    qualifying = template.create_qualifying_properties(signature)
    props = template.create_signed_properties(qualifying,
                                              name=signature_id +
                                              "-signedprops")
    template.add_claimed_role(props, "supplier")
    policy = GenericPolicyId(signature_policy_url,
                             signature_policy_description,
                             xmlsig.constants.TransformSha512)
    root.append(signature)
    ctx = XAdESContext(policy)
    ctx.load_pkcs12(
        crypto.load_pkcs12(b64decode(certificate_file), certificate_password))
    #with patch("xades.policy.urllib.urlopen") as mock:
    #    mock.return_value = b64decode(signature_policy_file).read()
    ctx.sign(signature)
    #ctx.verify(signature)

    #Complememto para corregir errores y posicionar bien los valores
    root.remove(signature)
    ext = "urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2"
    ds = "http://www.w3.org/2000/09/xmldsig#"
    #https://lxml.de/tutorial.html
    for element in root.iter("{%s}ExtensionContent2" % ext):
        element.append(signature)
        element.tag = "{%s}ExtensionContent" % ext

    for element in root.iter("{%s}SignatureValue" % ds):
        element.attrib['Id'] = signature_id + "-sigvalue"
    #https://www.decalage.info/en/python/lxml-c14n
    output = StringIO()
    root.getroottree().write_c14n(output)
    root = output.getvalue()

    return root
Ejemplo n.º 7
0
    def action_sign(self, xml_string_data):
        def new_range():
            return randrange(100000, 999999)

        filecontent = base64.b64decode(self.file_content)
        try:
            private_key = crypto.load_privatekey(
                crypto.FILETYPE_PEM, self.private_key.encode("ascii"),
                self.password.encode())
            p12 = crypto.load_pkcs12(filecontent, self.password)
        except Exception as ex:
            _logger.warning(tools.ustr(ex))
            raise UserError(
                _("Error opening the signature, possibly the signature key has been entered incorrectly or the file "
                  "is not supported. \n%s ") % (tools.ustr(ex)))
        data = open(xml_string_data.name, 'rb')
        xslt_content = data.read()
        doc = etree.fromstring(xslt_content)
        signature_id = f"Signature{new_range()}"
        signature_property_id = f"{signature_id}-SignedPropertiesID{new_range()}"
        certificate_id = f"Certificate{new_range()}"
        reference_uri = f"Reference-ID-{new_range()}"
        signature = xmlsig.template.create(
            xmlsig.constants.TransformInclC14N,
            xmlsig.constants.TransformRsaSha1,
            signature_id,
        )
        xmlsig.template.add_reference(
            signature,
            xmlsig.constants.TransformSha1,
            name=f"SignedPropertiesID{new_range()}",
            uri=f"#{signature_property_id}",
            uri_type="http://uri.etsi.org/01903#SignedProperties",
        )
        xmlsig.template.add_reference(signature,
                                      xmlsig.constants.TransformSha1,
                                      uri=f"#{certificate_id}")
        ref = xmlsig.template.add_reference(signature,
                                            xmlsig.constants.TransformSha1,
                                            name=reference_uri,
                                            uri="#comprobante")
        xmlsig.template.add_transform(ref, xmlsig.constants.TransformEnveloped)
        ki = xmlsig.template.ensure_key_info(signature, name=certificate_id)
        data = xmlsig.template.add_x509_data(ki)
        xmlsig.template.x509_data_add_certificate(data)
        xmlsig.template.add_key_value(ki)
        qualifying = template.create_qualifying_properties(signature,
                                                           name=signature_id)
        props = template.create_signed_properties(qualifying,
                                                  name=signature_property_id)
        signed_do = template.ensure_signed_data_object_properties(props)
        template.add_data_object_format(
            signed_do,
            f"#{reference_uri}",
            description="contenido comprobante",
            mime_type="text/xml",
        )
        doc.append(signature)
        x509 = self._extract_x509(p12)
        if x509 is not None:
            p12.set_certificate(x509)
            p12.set_privatekey(private_key)
        ctx = XAdESContext(ImpliedPolicy(xmlsig.constants.TransformSha1))
        ctx.load_pkcs12(p12)
        ctx.sign(signature)
        ctx.verify(signature)
        return etree.tostring(doc, encoding="UTF-8",
                              pretty_print=True).decode()