def assina_xml(self, xml_element, reference, key_name=None): cert, key = extract_cert_and_key_from_pfx(self.arquivo, self.senha) for element in xml_element.iter("*"): if element.text is not None and not element.text.strip(): element.text = None signer = 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 = {} ns[None] = signer.namespaces['ds'] signer.namespaces = ns ref_uri = ('#%s' % reference) if reference else None signed_root = signer.sign(xml_element, key=key, cert=cert, reference_uri=ref_uri, key_name=key_name) 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)
def assina_xml(self, xml_element, reference): cert, key = extract_cert_and_key_from_pfx(self.arquivo, self.senha) for element in xml_element.iter("*"): if element.text is not None and not element.text.strip(): element.text = None signer = XMLSigner( method=signxml.methods.enveloped, signature_algorithm=u"rsa-sha1", digest_algorithm=u'sha1', c14n_algorithm=u'http://www.w3.org/TR/2001/REC-xml-c14n-20010315') ns = {} ns[None] = signer.namespaces['ds'] signer.namespaces = ns element_to_be_signed = xml_element.getchildren()[0].getchildren()[0] signed_root = signer.sign( element_to_be_signed, key=key.encode(), cert=cert.encode()) 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 = xml_element.getchildren()[0] parent.append(signature) return etree.tostring(xml_element, encoding=str)
def assina_xml(self, xml_element, reference): cert, key = extract_cert_and_key_from_pfx(self.arquivo, self.senha) for element in xml_element.iter("*"): if element.text is not None and not element.text.strip(): element.text = None signer = 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 = {} ns[None] = signer.namespaces["ds"] signer.namespaces = ns ref_uri = ("#%s" % reference) if reference else None signed_root = signer.sign(xml_element, key=key.encode(), cert=cert.encode(), reference_uri=ref_uri) if reference: element_signed = signed_root.find(".//*[@Id='%s']" % reference) signature = (signed_root.find(".//*[@URI='#%s']" % reference).getparent().getparent()) if element_signed is not None and signature is not None: parent = element_signed.getparent() parent.append(signature) return etree.tostring(signed_root, encoding=str)
def assinar(self, xml, retorna_string=False): # busca tag que tem id(reference_uri), logo nao importa se tem namespace reference = xml.find(".//*[@Id]").attrib['Id'] # retira acentos xml_str = remover_acentos( etree.tostring(xml, encoding="unicode", pretty_print=False)) xml = etree.fromstring(xml_str) signer = 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 = {None: signer.namespaces['ds']} signer.namespaces = ns ref_uri = ('#%s' % reference) if reference else None signed_root = signer.sign(xml, key=self.key, cert=self.cert, reference_uri=ref_uri) ns = {'ns': NAMESPACE_SIG} # coloca o certificado na tag X509Data/X509Certificate tagX509Data = signed_root.find('.//ns:X509Data', namespaces=ns) etree.SubElement(tagX509Data, 'X509Certificate').text = self.cert if retorna_string: return etree.tostring(signed_root, encoding="unicode", pretty_print=False) else: return signed_root
def signWithCert(self, stringXml, key, returnString=True): xmlBuffer = etree.fromstring(stringXml) tree = etree.fromstring(stringXml) reference = tree.findall(".//*[@Id]") cert = self.extractCertContent() key = open(key, "rb").read() signer = 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 = {None: signer.namespaces['ds']} signer.namespaces = ns refUri = ('#%s' % reference) if reference else None signedRoot = signer.sign( xmlBuffer, key=key, cert=cert, reference_uri=refUri) ns = {'ns': NAMESPACE_SIG} # Insert the cert file buffered data (content) into specified tags X509Data/X509Certificate tagX509Data = signedRoot.find('.//ns:X509Data', namespaces=ns) etree.SubElement(tagX509Data, 'X509Certificate').text = cert if returnString: xmlEnvelope = etree.tostring(signedRoot, encoding="unicode", pretty_print=False) return xmlEnvelope else: return signedRoot
def assina_xml(self, xml_element, reference): cert, key = extract_cert_and_key_from_pfx(self.arquivo, self.senha) for element in xml_element.iter("*"): if element.text is not None and not element.text.strip(): element.text = None signer = 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 = {} ns[None] = signer.namespaces['ds'] signer.namespaces = ns ref_uri = ('#%s' % reference) if reference else None signed_root = signer.sign( xml_element, key=key, cert=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)
def assinar(self, xml, retorna_string=False): # busca tag que tem id(reference_uri), logo nao importa se tem namespace reference = xml.find(".//*[@Id]").attrib['Id'] #print('Referencia: ',reference) # retira acentos xml_str = remover_acentos(etree.tostring(xml, encoding="unicode", pretty_print=False)) xml = etree.fromstring(xml_str) signer = 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 = {None: signer.namespaces['ds']} signer.namespaces = ns #print('Chave......: ',self.key) #print('*',200) #print('Certificado: ',self.cert) ref_uri = ('#%s' % reference) if reference else None signed_root = signer.sign( xml, key=self.key, cert=self.cert, reference_uri=ref_uri) ns = {'ns': NAMESPACE_SIG} # coloca o certificado na tag X509Data/X509Certificate tagX509Data = signed_root.find('.//ns:X509Data', namespaces=ns) etree.SubElement(tagX509Data, 'X509Certificate').text = self.cert #print('Assinatura: ',etree.tostring(signed_root, encoding="unicode", pretty_print=False) ) if retorna_string: return etree.tostring(signed_root, encoding="unicode", pretty_print=False) else: return signed_root
def assina_xml(self, xml_element): cert, key = extract_cert_and_key_from_pfx(self.arquivo, self.senha) for element in xml_element.iter("*"): if element.text is not None and not element.text.strip(): element.text = None signer = XMLSigner( method=methods.enveloped, signature_algorithm=u"rsa-sha1", digest_algorithm=u"sha1", c14n_algorithm=u"http://www.w3.org/TR/2001/REC-xml-c14n-20010315", ) ns = {} ns[None] = signer.namespaces["ds"] signer.namespaces = ns element_signed = xml_element.find(".//{http://nfse.goiania.go.gov.br/xsd/nfse_gyn_v02.xsd}Rps") signed_root = signer.sign( xml_element, key=key.encode(), cert=cert.encode() ) signature = signed_root.find( ".//{http://www.w3.org/2000/09/xmldsig#}Signature" ) if element_signed is not None and signature is not None: parent = xml_element.getchildren()[0] parent.append(signature) return etree.tostring(xml_element, encoding=str)
def test_signxml_changing_signature_namespace_prefix(self): data = etree.parse(self.example_xml_files[0]).getroot() signer = XMLSigner() signer.namespaces = dict(digi_sign=namespaces['ds']) signed = signer.sign(data, key=self.keys["rsa"]) signed_data = etree.tostring(signed) expected_match = ("<digi_sign:Signature xmlns:" "digi_sign=\"%s\">") % namespaces['ds'] self.assertTrue(re.search(expected_match.encode('ascii'), signed_data))
def test_signxml_changing_signature_namespace_prefix(self): data = etree.parse(self.example_xml_files[0]).getroot() signer = XMLSigner() signer.namespaces = dict(digi_sign=namespaces['ds']) signed = signer.sign(data, key=self.keys["rsa"]) signed_data = etree.tostring(signed) expected_match = ("<digi_sign:Signature xmlns:" "digi_sign=\"%s\">") % namespaces['ds'] self.assertTrue(re.search(expected_match.encode('ascii'), signed_data))
def assina_xml(self, xml): ##Modificado para utilizar o signxml ao inves do libxml2 e xmlsec from signxml import XMLSigner from signxml import methods xml = self._prepara_doc_xml(xml) doc_xml = lxml.etree.fromstring(xml.encode('utf-8')) #buscando chave de acesso no documento e retiranto TAG Signature chave_de_acesso = self._ler_chave_acesso(doc_xml) if chave_de_acesso is None: raise ValueError( 'Nao foi possivel encontrar a Tag para a assinatura.') #String para bytes para a leitura no signxml chave = self.chave.encode('utf-8') certificado = self.certificado.encode('utf-8') signer = XMLSigner( method=methods.enveloped, signature_algorithm='rsa-sha1', digest_algorithm='sha1', c14n_algorithm='http://www.w3.org/TR/2001/REC-xml-c14n-20010315') #Retirar os prefixos ds: da assinatura ns = {} ns[None] = signer.namespaces['ds'] signer.namespaces = ns #Assina o documento signed_doc = signer.sign(doc_xml, key=chave, cert=certificado, reference_uri='#{0}'.format(chave_de_acesso)) #Selecionar apenas a tag Signature do documento. signature_tag = None for child in signed_doc: if 'Signature' in child.tag: signature_tag = child if signature_tag is None: raise ("Assinatura nao encontrada.") signature_tag = lxml.etree.tostring(signature_tag).decode('utf-8') signature_tag = self._finaliza_xml(signature_tag) return signature_tag
def assina_xml(self, xml_element, reference): cert, key = extract_cert_and_key_from_pfx(self.arquivo, self.senha) for element in xml_element.iter("*"): if element.text is not None and not element.text.strip(): element.text = None signer = 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 = {} ns[None] = signer.namespaces['ds'] signer.namespaces = ns signed_root = signer.sign( xml_element, key=key, cert=cert, reference_uri=('#%s' % reference)) if len(signed_root) > 3: signed_root[2].append(signed_root[3]) return etree.tostring(signed_root)