示例#1
0
    def assina_xml2(self, xml_element, reference):
        for element in xml_element.iter("*"):
            if element.text is not None and not element.text.strip():
                element.text = None

        signer = signxml.XMLSigner(
            method=signxml.methods.enveloped,
            signature_algorithm="rsa-sha1",
            digest_algorithm='sha1',
            c14n_algorithm='http://www.w3.org/TR/2001/REC-xml-c14n-20010315')

        ns = dict()
        ns[None] = signer.namespaces['ds']
        signer.namespaces = ns

        ref_uri = ('#%s' % reference) if reference else None

        signed_root = signer.sign(xml_element,
                                  key=self.certificado._chave,
                                  cert=self.certificado._cert,
                                  reference_uri=ref_uri)

        if reference:
            element_signed = signed_root.find(".//*[@Id='%s']" % reference)
            signature = signed_root.find(
                ".//{http://www.w3.org/2000/09/xmldsig#}Signature")

            if element_signed is not None and signature is not None:
                parent = element_signed.getparent()
                parent.append(signature)
        return etree.tostring(signed_root, encoding='utf8', method='xml')
示例#2
0
 def sign(root, uri):
     cert = open(config.CERTFILE).read()
     key = open(config.KEYFILE).read()
     return signxml.XMLSigner(signature_algorithm=SIGNATURE_ALGORITHM,
                              digest_algorithm=DIGEST_ALGORITHM,
                              c14n_algorithm=C14N_ALGORITHM).sign(
                                  root,
                                  cert=cert,
                                  key=key,
                                  reference_uri=uri)
def sign_permission_artefact(xml_root, private_key=MOCK_DGCA_PRIVATE_KEY, certificate=MOCK_DGCA_CERTIFICATE):
    """
    Sign the permission artefact xml with the private key stored .
    Optionally pass a different key path to sign with a different key
    :param xml_root: the xml root object to sign
    :param private_key: the path to the private key to perform signing
    :return: the signed XML root object. Note - this needs to be saved as a file
    """
    root = xml_root.getroot()

    with open(private_key, 'rb') as f, open(certificate) as c:
        key = f.read()
        cert = c.read()
    signed_root = sx.XMLSigner()
    ns = {}
    ns[None] = signed_root.namespaces['ds']
    signed_root.namespaces = ns
    signed_root = signed_root.sign(root, key=key, cert=cert)
    return signed_root
示例#4
0
    def assina_xml(self, xml):
        xml = self._prepara_doc_xml(xml)

        assinatura = Signature()
        assinatura.xml = xml

        #
        # Tiramos a tag de assinatura, o signxml vai colocar de novo
        #
        if '<Signature ' in xml:
            partes = xml.split('<Signature ')
            xml_sem_assinatura = ''.join(partes[:-1])
            partes = partes[-1].split('</Signature>')
            xml_sem_assinatura += ''.join(partes[-1])
            xml = xml_sem_assinatura

        #
        # Colocamos o texto no avaliador XML
        #
        doc_xml = etree.fromstring(xml.encode('utf-8'))

        assinador = signxml.XMLSigner(
            method=signxml.methods.enveloped,
            signature_algorithm='rsa-sha1',
            digest_algorithm='sha1',
            c14n_algorithm='http://www.w3.org/TR/2001/REC-xml-c14n-20010315')
        assinador.namespaces = {None: assinador.namespaces['ds']}

        doc_xml = assinador.sign(doc_xml,
                                 key=self.chave,
                                 cert=self.certificado,
                                 reference_uri=assinatura.URI)

        #
        # Retransforma o documento xml em texto
        #
        xml = etree.tostring(doc_xml)

        xml = self._finaliza_xml(xml)

        return xml
示例#5
0
def sign_x509(xml,
              key,
              certificate,
              algorithm=None,
              digest_algorithm=None,
              canonicalization_method=None):
    """Sign PSKC data using X.509 certificate and private key.

    xml: an XML document
    key: the private key in binary format
    certificate: the X.509 certificate
    """
    import signxml
    algorithm = algorithm or 'rsa-sha256'
    digest_algorithm = digest_algorithm or 'sha256'
    canonicalization_method = (
        canonicalization_method
        or signxml.XMLSignatureProcessor.default_c14n_algorithm)
    return signxml.XMLSigner(
        method=signxml.methods.enveloped,
        signature_algorithm=algorithm.rsplit('#', 1)[-1].lower(),
        digest_algorithm=digest_algorithm.rsplit('#', 1)[-1].lower(),
        c14n_algorithm=canonicalization_method,
    ).sign(xml, key=key, cert=certificate)
示例#6
0
def pretty_print_lxml(label, lxml_string):
    if label:
        print(label)
    print((etree_.tostring(lxml_string, pretty_print=True)))


HAND_BUILT_PAYLOAD = False

signed_object_xml = open('sample_for_crypto_experiment.xml', 'rb').read()
signed_object_lxml = etree_.fromstring(signed_object_xml)

pretty_print_lxml('Original XML to be signed:', signed_object_lxml)
# Use "detached method": the signature lives alonside the signed object in the XML element tree.
# Use c14n "exclusive canonicalization": the signature is independent of namespace inclusion/exclusion.
signer = signxml.XMLSigner(method=signxml.methods.detached,
                           c14n_algorithm='http://www.w3.org/2001/10/xml-exc-c14n#')
signature_lxml = signer.sign(signed_object_lxml,
                             key=open(CERTS_DIRECTORY + KEY_FILENAME, 'rb').read(),
                             cert=open(CERTS_DIRECTORY + CERT_FILENAME, 'rb').read(),
                             key_name='123')
pretty_print_lxml('Signed root:', signature_lxml)
signature_xml = etree_.tostring(signature_lxml)

if HAND_BUILT_PAYLOAD:
    payload = XML_PREFIX + PAYLOAD_START_TAG + signature_xml + signed_object_xml + PAYLOAD_END_TAG
else:
    payload = etree_.Element("{http://openadr.org/oadr-2.0b/2012/07}oadrPayload",
                             nsmap=signed_object_lxml.nsmap)
    payload.append(signature_lxml)
    payload.append(signed_object_lxml)
    pretty_print_lxml('Payload:', payload)
#!/usr/bin/env vpython3
# *-* coding: utf-8 *-*
from lxml import etree
import signxml

cert = open("demo2_user1.crt.pem").read()
key = open("demo2_user1.key.pem").read()
data = open("xml.xml", "rb").read()
root = etree.fromstring(data)
signed_root = signxml.XMLSigner(method=signxml.methods.enveloped).sign(
    root, key=key, cert=cert, passphrase=b"1234")
verified_data = (signxml.XMLVerifier().verify(
    signed_root, ca_pem_file="demo2_ca.crt.pem").signed_xml)

xml = etree.tostring(signed_root,
                     encoding="UTF-8",
                     xml_declaration=True,
                     standalone=False)
open("xml-xmlsigner-enveloped.xml", "wb").write(xml)

xml = etree.tostring(
    signed_root,
    encoding="UTF-8",
    xml_declaration=True,
    standalone=False,
    pretty_print=True,
)
open("xml-xmlsigner-enveloped1.xml", "wb").write(xml)
示例#8
0
    def assina_xml(self,
                   xml,
                   URI='',
                   numero_assinatura=0,
                   doctype='',
                   atributo='Id',
                   tag='',
                   namespaces={},
                   formatado=False):
        if not formatado:
            xml = tira_formatacao(xml)

        xml = self._prepara_doc_xml(xml, doctype=doctype)

        if 'None' in namespaces:
            namespaces[None] = namespaces['None']

        #
        # Colocamos o texto no avaliador XML
        #
        doc_xml = etree.fromstring(xml.encode('utf-8'))

        #if not URI:
        #assinaturas = doc_xml.xpath('//sig:Signature', namespaces=NAMESPACES)
        #assinatura = assinaturas[numero_assinatura]
        #referencias = assinatura.xpath('//sig:Reference', namespaces=NAMESPACES)
        #referencia = referencias[0]
        #URI = referencia.attrib['URI']
        #if URI and URI[0] == '#':
        #URI = URI[1:]

        if URI:
            a_assinar = doc_xml.xpath("//*[@" + atributo + "='" + URI + "']")
            a_assinar = a_assinar[0]
            a_assinar = a_assinar.getparent()
        elif tag:
            a_assinar = doc_xml.xpath("//" + tag, namespaces=namespaces)
            a_assinar = a_assinar[0]
            a_assinar = a_assinar.getparent()

        #assinaturas = a_assinar.xpath('//sig:Signature', namespaces=NAMESPACES)
        #for assinatura in assinaturas:
        #if assinatura.getparent() == a_assinar:
        #a_assinar.remove(assinatura)

        assinador = signxml.XMLSigner(
            method=signxml.methods.enveloped,
            signature_algorithm='rsa-sha1',
            digest_algorithm='sha1',
            c14n_algorithm='http://www.w3.org/TR/2001/REC-xml-c14n-20010315')
        assinador.namespaces = {None: assinador.namespaces['ds']}

        if URI:
            assinado = assinador.sign(a_assinar,
                                      key=self.chave,
                                      cert=self.certificado,
                                      reference_uri=URI)
        else:
            assinado = assinador.sign(a_assinar,
                                      key=self.chave,
                                      cert=self.certificado)

        if a_assinar.getparent() is not None:
            a_assinar.getparent().replace(a_assinar, assinado)
        else:
            doc_xml = assinado

        #
        # Retransforma o documento xml em texto
        #
        xml = etree.tounicode(doc_xml)

        xml = self._finaliza_xml(xml, doctype=doctype)

        return xml