Signing Nfs-e in C# generates error Poorly formed Reference Element

Asked

Viewed 1,142 times

6

out of nowhere my code in C# stopped signing the Nfs-e of Curitiba. In the code line below, gives the error:

signedXml.ComputeSignature();

Errro

Elemento Reference mal formado

Does anyone know if it might be something to do with the certificate? Because it always worked and stopped out of the blue, without updating the system.

Signing

private void Assinar(XmlDocument doc, X509Certificate2 certificado, string tag)
{
    XmlNodeList listaTagsAssinar = doc.GetElementsByTagName(tag);
    SignedXml signedXml;

    foreach (XmlElement infNFe in listaTagsAssinar)
    {

        // obter o valor da propriedade "Id" da tag que será assinada

        string id = "";
        if (infNFe.HasAttribute("id"))
            id = infNFe.Attributes.GetNamedItem("id").Value;
        else if (infNFe.HasAttribute("Id"))
            id = infNFe.Attributes.GetNamedItem("Id").Value;
        else if (infNFe.HasAttribute("ID"))
            id = infNFe.Attributes.GetNamedItem("ID").Value;
        else if (infNFe.HasAttribute("iD"))
            id = infNFe.Attributes.GetNamedItem("iD").Value;
        else
            throw new Exception("Tag " + tag + " não tem atributo Id");


        signedXml = new SignedXml(infNFe);
        signedXml.SigningKey = certificado.PrivateKey;

        // Transformações p/ DigestValue da Nota
        Reference reference = new Reference("#" + id);
        reference.AddTransform(new XmlDsigEnvelopedSignatureTransform());

        signedXml.SignedInfo.CanonicalizationMethod += "#WithComments";

        //reference.AddTransform(new XmlDsigC14NTransform());
        signedXml.AddReference(reference);

        KeyInfo keyInfo = new KeyInfo();
        keyInfo.AddClause(new KeyInfoX509Data(certificado));
        signedXml.KeyInfo = keyInfo;

        // gerar o valor da assinatura
        signedXml.ComputeSignature();

        // criar elemento <Signature>
        XmlElement xmlSignature = doc.CreateElement("Signature", "http://www.w3.org/2000/09/xmldsig#");

        // criar Id da tag <Signature>
        XmlAttribute idAssinatura = doc.CreateAttribute("Id");
        idAssinatura.Value = "Ass_" + id.Replace(":", "_");
        xmlSignature.Attributes.InsertAfter(idAssinatura, xmlSignature.GetAttributeNode("xmlns"));

        // gerar elemento <SignedInfo>
        XmlElement xmlSignedInfo = signedXml.SignedInfo.GetXml();

        // gerar elemento <KeyInfo>
        XmlElement xmlKeyInfo = signedXml.KeyInfo.GetXml();

        // compor nó <SignatureValue>
        XmlElement xmlSignatureValue = doc.CreateElement("SignatureValue", xmlSignature.NamespaceURI);
        string signBase64 = Convert.ToBase64String(signedXml.Signature.SignatureValue);
        XmlText text = doc.CreateTextNode(signBase64);
        xmlSignatureValue.AppendChild(text);

        // incluir nós filhos da assinatura
        xmlSignature.AppendChild(doc.ImportNode(xmlSignedInfo, true));
        xmlSignature.AppendChild(xmlSignatureValue);
        xmlSignature.AppendChild(doc.ImportNode(xmlKeyInfo, true));

        // incluir assinatura no documento
        infNFe.ParentNode.AppendChild(xmlSignature);
    }
}

Call data

Xmldoc

<?xml version="1.0" encoding="utf-16"?>
<EnviarLoteRpsEnvio xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <LoteRps Id="123456" xmlns="http://www.e-governeapps2.com.br/">
    <NumeroLote>620</NumeroLote>
    <Cnpj>01188703000158</Cnpj>
    <InscricaoMunicipal>000000003311870</InscricaoMunicipal>
    <QuantidadeRps>1</QuantidadeRps>
    <ListaRps>
      <Rps>
        <InfRps>
          <IdentificacaoRps>
            <Numero>620</Numero>
            <Serie>RPS</Serie>
            <Tipo>1</Tipo>
          </IdentificacaoRps>
          <DataEmissao>2016-03-09T09:00:48.923</DataEmissao>
          <NaturezaOperacao>1</NaturezaOperacao>
          <RegimeEspecialTributacao>1</RegimeEspecialTributacao>
          <OptanteSimplesNacional>2</OptanteSimplesNacional>
          <IncentivadorCultural>2</IncentivadorCultural>
          <Status>1</Status>
          <Servico>
            <Valores>
              <ValorServicos>862.81</ValorServicos>
              <ValorDeducoes>0.00</ValorDeducoes>
              <ValorPis>5.61</ValorPis>
              <ValorCofins>25.88</ValorCofins>
              <ValorInss>0.00</ValorInss>
              <ValorIr>12.94</ValorIr>
              <ValorCsll>8.63</ValorCsll>
              <IssRetido>2</IssRetido>
              <ValorIss>43.14</ValorIss>
              <ValorIssRetido>0.00</ValorIssRetido>
              <OutrasRetencoes>0.00</OutrasRetencoes>
              <BaseCalculo>862.81</BaseCalculo>
              <Aliquota>0.05</Aliquota>
              <ValorLiquidoNfse>809.75</ValorLiquidoNfse>
              <DescontoIncondicionado>0.00</DescontoIncondicionado>
              <DescontoCondicionado>0.00</DescontoCondicionado>
            </Valores>
            <ItemListaServico>0408</ItemListaServico>
            <CodigoCnae>0</CodigoCnae>
            <Discriminacao>CONSULTA MÉDICA     Qtde.: 9     Vlr. Unit. R$ 30,00     Vlr. Total R$ 270,00\r\nREF.02/2016-Euro Import.\r\nCONSULTA MÉDICA     Qtde.: 4     Vlr. Unit. R$ 30,00     Vlr. Total R$ 120,00\r\nREF.02/2016.-SUL IMPORT\r\nCONSULTA MÉDICA     Qtde.: 15     Vlr. Unit. R$ 30,00     Vlr. Total R$ 450,00\r\nRef.Fevereiro/2016 - AR SUDESTE\r\nAUDIOMETRIA     Qtde.: 1     Vlr. Unit. R$ 15,00     Vlr. Total R$ 15,00\r\nRef.Fevereiro/2016 - Sul Import\r\nEXS. LABORATÓRIO     Qtde.: 1     Vlr. Unit. R$ 7,81     Vlr. Total R$ 7,81\r\nRef.FEVEREIRO/2016 -Sul Import\r\n\r\nPara pagamento, fazer depósito:\r\nAUDIOMED - Banco Itaú Ag 3702 C/C 04568-7\r\nVencimento da NF: 30/03/2016\r\nConforme Lei Federal 12.741, informamos o percentual de impostos incidentes sobre esta nota fiscal: 16,33%</Discriminacao>
            <CodigoMunicipio>4106902</CodigoMunicipio>
          </Servico>
          <Prestador>
            <Cnpj>01188703000158</Cnpj>
            <InscricaoMunicipal>000000003311870</InscricaoMunicipal>
          </Prestador>
          <Tomador>
            <IdentificacaoTomador>
              <CpfCnpj>
                <Cnpj>07318719000114</Cnpj>
              </CpfCnpj>
            </IdentificacaoTomador>
            <RazaoSocial>AVANTI ENGENHARIA DE SEGURANÇA E SAUDE OCUPACIONAL</RazaoSocial>
            <Endereco>
              <Endereco>R: Parque Domingos Luis</Endereco>
              <Numero>141</Numero>
              <Bairro>Jardim São Paulo</Bairro>
              <CodigoMunicipio>3550308</CodigoMunicipio>
              <Uf>SP</Uf>
              <Cep>2043081</Cep>
            </Endereco>
            <Contato>
              <Telefone>1122832308</Telefone>
              <Email>[email protected]; [email protected]</Email>
            </Contato>
          </Tomador>
        </InfRps>
      </Rps>
    </ListaRps>
  </LoteRps>
</EnviarLoteRpsEnvio>

Tag

Loterps

  • 1

    @Bacco added more data

  • It’s gotten a lot better. Let’s see if the people who have practice in C# can help. So if you need more details, they can comment here too.

  • In my case, I’m on Windows 10. At the beginning of the month it worked but from there to here we had updates and I think something inside the . NET has changed. I’ll continue the search....

  • I cannot answer, probably because my reputation is global (stackexchange) and not local. I followed it here: http://stackoverflow.com/questions/5099156/malformed-reference-element-when-adding-a-reference-based-on-an-id-attribute-w and it worked. I switched to nsManager.AddNamespace("x", "http://www.abrasf.org.br/nfse.xsd"); and doc.SelectSingleNode("//x:EnviarLoteRpsEnvio//x:LoteRps//x:ListaRps//x:Rps//x:InfRps[@Id=\"" + id + "\"]", nsManager)

  • Hello I think it’s because the ID starts with numbers. The correct is to start the ID with letters. See possible duplicate topic below: Digital Signature

  • my question is not duplicated, she was asked before this you spoke. See what I asked on 10/03 and your link on 16/03.

Show 1 more comment
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.