Error Signing XML NF 4.0

0

When you try to sign the XML for NF-e 4.0 authorization. at the time of signedXml.ComputeSignature(); it always returns me error. I did a test with Visual Studio 2013 it usually signs, but when I run the project it gives the error:

  

Invalid signature specified.

I do not know what else to do. I already changed the default signature links. Someone help me ? XML:

<enviNFe xmlns="http://www.portalfiscal.inf.br/nfe" versao="4.00">
  <idLote>000000000002403</idLote>
  <indSinc>0</indSinc>
  <NFe>
    <infNFe versao="4.00" Id="NFe31180525452301000934550010000024031000024039">
      <ide>
        <cUF>31</cUF>
        <cNF>00002403</cNF>
        <natOp>Venda de produção do estabelecimento originada de encomenda</natOp>
        <mod>55</mod>
        <serie>1</serie>
        <nNF>2403</nNF>
        <dhEmi>2018-05-14T09:46:56-03:00</dhEmi>
        <dhSaiEnt>2018-05-14T18:06:11-03:00</dhSaiEnt>
        <tpNF>1</tpNF>
        <idDest>2</idDest>
        <cMunFG>3170107</cMunFG>
        <tpImp>1</tpImp>
        <tpEmis>1</tpEmis>
        <cDV>9</cDV>
        <tpAmb>2</tpAmb>
        <finNFe>1</finNFe>
        <indFinal>1</indFinal>
        <indPres>9</indPres>
        <procEmi>0</procEmi>
        <verProc>1.00</verProc>
      </ide>
      <emit>
        <CNPJ>25452301000934</CNPJ>
        <xNome>NF-E EMITIDA EM AMBIENTE DE HOMOLOGACAO - SEM VALOR FISCAL</xNome>
        <xFant>NF-E EMITIDA EM AMBIENTE DE HOMOLOGACAO - SEM VALOR FISCAL</xFant>
        <enderEmit>
          <xLgr>ROD BR-050 KM</xLgr>
          <nro>145</nro>
          <xBairro>D INDUSTRIAL II</xBairro>
          <cMun>3170107</cMun>
          <xMun>UBERABA</xMun>
          <UF>MG</UF>
          <CEP>38064750</CEP>
          <fone>3433196643</fone>
        </enderEmit>
        <IE>0010218360193</IE>
        <CRT>3</CRT>
      </emit>
      <dest>
        <CPF>35840820997</CPF>
        <xNome>NF-E EMITIDA EM AMBIENTE DE HOMOLOGACAO - SEM VALOR FISCAL</xNome>
        <enderDest>
          <xLgr>RUA CEL CARLOS 1836</xLgr>
          <nro>-</nro>
          <xBairro>CENTRO</xBairro>
          <cMun>5006309</cMun>
          <xMun>PARANAÍBA</xMun>
          <UF>MS</UF>
          <CEP>79500000</CEP>
          <cPais>1058</cPais>
          <xPais>BRASIL</xPais>
          <fone>6736694777</fone>
        </enderDest>
        <indIEDest>2</indIEDest>
      </dest>
      <det nItem="1">
        <prod>
          <cProd>44393</cProd>
          <cEAN />
          <xProd>MACHO DE 13 A 24 MESES</xProd>
          <NCM>01022190</NCM>
          <CFOP>6116</CFOP>
          <uCom>CAB</uCom>
          <qCom>1.0000</qCom>
          <vUnCom>15000.0000000000</vUnCom>
          <vProd>15000.00</vProd>
          <cEANTrib />
          <uTrib>CAB</uTrib>
          <qTrib>1.0000</qTrib>
          <vUnTrib>15000.0000000000</vUnTrib>
          <indTot>1</indTot>
        </prod>
        <imposto>
          <ICMS>
            <ICMS40>
              <orig>0</orig>
              <CST>41</CST>
              <vICMSDeson>1500.00</vICMSDeson>
              <motDesICMS>9</motDesICMS>
            </ICMS40>
          </ICMS>
          <PIS>
            <PISAliq>
              <CST>01</CST>
              <vBC>0.00</vBC>
              <pPIS>0.00</pPIS>
              <vPIS>0.00</vPIS>
            </PISAliq>
          </PIS>
          <COFINS>
            <COFINSAliq>
              <CST>01</CST>
              <vBC>0.00</vBC>
              <pCOFINS>0.00</pCOFINS>
              <vCOFINS>0.00</vCOFINS>
            </COFINSAliq>
          </COFINS>
        </imposto>
      </det>
      <total>
        <ICMSTot>
          <vBC>0.00</vBC>
          <vICMS>0.00</vICMS>
          <vICMSDeson>1500.00</vICMSDeson>
          <vICMSUFDest>0.00</vICMSUFDest>
          <vFCP>0.00</vFCP>
          <vBCST>0.00</vBCST>
          <vST>0.00</vST>
          <vFCPST>0.00</vFCPST>
          <vFCPSTRet>0.00</vFCPSTRet>
          <vProd>15000.00</vProd>
          <vFrete>0.00</vFrete>
          <vSeg>0.00</vSeg>
          <vDesc>0.00</vDesc>
          <vII>0.00</vII>
          <vIPI>0.00</vIPI>
          <vIPIDevol>0.00</vIPIDevol>
          <vPIS>0.00</vPIS>
          <vCOFINS>0.00</vCOFINS>
          <vOutro>0.00</vOutro>
          <vNF>15000.00</vNF>
        </ICMSTot>
      </total>
      <transp>
        <modFrete>1</modFrete>
      </transp>
      <cobr>
        <dup>
          <nDup>1</nDup>
          <dVenc>2018-10-16</dVenc>
          <vDup>15000</vDup>
        </dup>
      </cobr>
      <pag>
        <detPag>
          <tPag>14</tPag>
          <vPag>15000</vPag>
        </detPag>
      </pag>
    </infNFe>
  </NFe>
</enviNFe>

Signing-in code:

public static void AssinarXML(string arqXMLAssinar, string tagAssinatura, string tagAtributoId)
{
        CryptoConfig.AddAlgorithm(typeof(RSAPKCS1SHA256SignatureDescription), "http://www.w3.org/2001/04/xmlenc#sha256");
        //CryptoConfig.AddAlgorithm(typeof(RSAPKCS1SHA256SignatureDescription), "http://www.w3.org/2000/09/xmldsig#rsa-sha1"); 
        X509Certificate2 x509Cert = new X509Certificate2(BLL.BLL.CaminhoCertificado(), "1234");            

        StreamReader SR = null;

        try
        {
            RemoveXmlns(arqXMLAssinar);

            //Abrir o arquivo XML a ser assinado e ler o seu conteúdo
            SR = File.OpenText(arqXMLAssinar);

            string xmlString = SR.ReadToEnd();
            SR.Close();
            SR = null;

            xmlString = xmlString.Replace('Ç', 'C');
            xmlString = xmlString.Replace('ç', 'c');

            xmlString = xmlString.Replace('Á', 'A');
            xmlString = xmlString.Replace('á', 'a');
            xmlString = xmlString.Replace('Â', 'A');
            xmlString = xmlString.Replace('â', 'a');
            xmlString = xmlString.Replace('Ã', 'A');
            xmlString = xmlString.Replace('ã', 'a');

            xmlString = xmlString.Replace('É', 'E');
            xmlString = xmlString.Replace('é', 'e');

            xmlString = xmlString.Replace('Í', 'I');
            xmlString = xmlString.Replace('í', 'i');

            xmlString = xmlString.Replace('Ó', 'O');
            xmlString = xmlString.Replace('ó', 'o');
            xmlString = xmlString.Replace('Ô', 'O');
            xmlString = xmlString.Replace('ô', 'o');
            xmlString = xmlString.Replace('Õ', 'O');
            xmlString = xmlString.Replace('õ', 'o');

            // Create a new XML document.
            XmlDocument doc = new XmlDocument
            {
                // Format the document to ignore white spaces.
                PreserveWhitespace = false
            };

            // Load the passed XML file using it’s name.
            doc.LoadXml(xmlString);

            if (doc.GetElementsByTagName(tagAssinatura).Count == 0)
            {
                throw new Exception("A tag de assinatura " + tagAssinatura.Trim() + " não existe no XML. (Código do Erro: 5)");
            }
            else if (doc.GetElementsByTagName(tagAtributoId).Count == 0)
            {
                throw new Exception("A tag de assinatura " + tagAtributoId.Trim() + " não existe no XML. (Código do Erro: 4)");
            }
            // Existe mais de uma tag a ser assinada
            else
            {
                XmlDocument XMLDoc;

                XmlNodeList lists = doc.GetElementsByTagName(tagAssinatura);
                //XmlNode listRPS = null;

                foreach (XmlNode nodes in lists)
                {
                    foreach (XmlNode childNodes in nodes.ChildNodes)
                    {
                        if (!childNodes.Name.Equals(tagAtributoId))
                            continue;

                        // Create a reference to be signed
                        Reference reference = new Reference();


                        reference.Uri = "";

                        // pega o uri que deve ser assinada                                       
                        XmlElement childElemen = (XmlElement)childNodes;
                        if (childElemen.GetAttributeNode("Id") != null)
                        {
                            reference.Uri = "#" + childElemen.GetAttributeNode("Id").Value;
                        }
                        else if (childElemen.GetAttributeNode("id") != null)
                        {
                            reference.Uri = "#" + childElemen.GetAttributeNode("id").Value;
                        }

                        // Create a SignedXml object.
                        SignedXml signedXml = new SignedXml(doc);
                        signedXml.SigningKey = x509Cert.PrivateKey;
                        //signedXml.SignedInfo.SignatureMethod = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256";
                        //signedXml.SignedInfo.SignatureMethod = "http://www.w3.org/2000/09/xmldsig#rsa-sha1";

                        // Add an enveloped transformation to the reference.
                        //XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();
                        reference.AddTransform(new XmlDsigEnvelopedSignatureTransform());

                        //XmlDsigC14NTransform c14 = new XmlDsigC14NTransform();
                        reference.AddTransform(new XmlDsigC14NTransform());
                        //reference.DigestMethod = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256";
                        //reference.DigestMethod = "http://www.w3.org/2000/09/xmldsig#rsa-sha1";

                        // Add the reference to the SignedXml object.
                        signedXml.AddReference(reference);

                        // Create a new KeyInfo object
                        KeyInfo keyInfo = new KeyInfo();

                        // Load the certificate into a KeyInfoX509Data object
                        // and add it to the KeyInfo object.
                        keyInfo.AddClause(new KeyInfoX509Data(x509Cert));

                        // Add the KeyInfo object to the SignedXml object.
                        signedXml.KeyInfo = keyInfo;

                        signedXml.ComputeSignature();

                        // Get the XML representation of the signature and save
                        // it to an XmlElement object.
                        XmlElement xmlDigitalSignature = signedXml.GetXml();

                        // Gravar o elemento no documento XML
                        nodes.AppendChild(doc.ImportNode(xmlDigitalSignature, true));
                    }
                }

                XMLDoc = new XmlDocument();
                XMLDoc.PreserveWhitespace = false;
                XMLDoc = doc;

                // Atualizar a string do XML já assinada
                string StringXMLAssinado = XMLDoc.OuterXml;

                // Gravar o XML Assinado no HD
                StreamWriter SW_2 = File.CreateText(arqXMLAssinar);
                SW_2.Write(StringXMLAssinado);
                SW_2.Close();
            }
        }
        catch(CryptographicException ex)
        {
            //MessageBox.Show(ex.Message + " - " + ex.InnerException.ToString());
            throw new CryptographicException("Erro ao assinar a XML",ex);
        }
        finally
        {
            if (SR != null)
                SR.Close();
        }
    }

I do not know what else to do. Does anyone have any ideas ? Note: the codes commented on by the W3 links are the ones I have already tested. NOTE: When I hide the links from the following error: "Could not create hash algorithm object."

    
asked by anonymous 14.05.2018 / 15:00

0 answers