eSocial: Invalid Subscription . NET Framework

Asked

Viewed 386 times

2

Invalid Signature

Good afternoon, I have a problem transmitting the information to the webservices of eSocial. The process I do is the following: the events Xmls are generated on the server, returned to an application that runs on the client machine and is responsible for signing the events and carrying the transmission to eSocial. The transmission of the batch is made and received successfully, but when consulting the information by the query webservice ( by the return delivery receipt in the shipment ) a code error is returned 142 and description Invalid event signature. Suggested Actions: Check for event changes after signing. Check for subscription validity.

I will put down the submitted file and the method responsible for signing. (The certificate data were omitted)

<eSocial xmlns="http://www.esocial.gov.br/schema/lote/eventos/envio/v1_1_1">
  <envioLoteEventos grupo="2">
    <ideEmpregador>
      <tpInsc>1</tpInsc>
      <nrInsc>95784204000177</nrInsc>
    </ideEmpregador>
    <ideTransmissor>
      <tpInsc>1</tpInsc>
      <nrInsc>05964161000119</nrInsc>
    </ideTransmissor>
    <eventos>
      <evento Id="ID1957842040001772018121314262900000">
        <eSocial xmlns="http://www.esocial.gov.br/schema/evt/evtToxic/v02_05_00">
          <evtToxic Id="ID1957842040001772018120609352600000">
            <ideEvento>
              <indRetif>0</indRetif>
              <tpAmb>2</tpAmb>
              <procEmi>1</procEmi>
              <verProc>01.00.00</verProc>
            </ideEvento>
            <ideEmpregador>
              <tpInsc>1</tpInsc>
              <nrInsc>95784204000177</nrInsc>
            </ideEmpregador>
            <ideVinculo>
              <cpfTrab>56641686094</cpfTrab>
              <nisTrab>12025177234</nisTrab>
              <matricula>621</matricula>
            </ideVinculo>
            <toxicologico>
              <dtExame>2018-12-06</dtExame>
              <indRecusa>S</indRecusa>
            </toxicologico>
          </evtToxic>
          <Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
            <SignedInfo>
              <CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315" />
              <SignatureMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256" />
              <Reference URI="">
                <Transforms>
                  <Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature" />
                  <Transform Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315" />
                </Transforms>
                <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256" />
                <DigestValue>...</DigestValue>
              </Reference>
            </SignedInfo>
            <SignatureValue>...</SignatureValue>
            <KeyInfo>
              <X509Data>
                <X509Certificate>...</X509Certificate>
              </X509Data>
            </KeyInfo>
          </Signature>
        </eSocial>
      </evento>
    </eventos>
  </envioLoteEventos>
</eSocial>

Here the code responsible for creating the lot and then signing the event.

var cl = new WSEsocial.Envio.ServicoEnviarLoteEventosClient();

cl.ClientCredentials.ClientCertificate.SetCertificate(cert.SubjectName.Name, System.Security.Cryptography.X509Certificates.StoreLocation.CurrentUser, System.Security.Cryptography.X509Certificates.StoreName.My);

XmlElement _getXmlElement(string xml)
{
  var d = new XmlDocument();
  d.LoadXml(_serviceSign.Sign(cert, xml).OuterXml);
  return d.DocumentElement;
}

var lote = new eSocial()
{
  envioLoteEventos = new eSocialEnvioLoteEventos()
  {
    grupo = (sbyte)model.GrupoEvento,
    ideEmpregador = new TIdeEmpregador()
    {
      nrInsc = model.UnidadeInsc,
      tpInsc = (sbyte)model.TipoInsc
    },
    ideTransmissor = new TIdeTransmissor()
    {
      nrInsc = cnpj,
      tpInsc = (sbyte)1
    },
    eventos = new eSocialEnvioLoteEventosEventos()
    {
      evento = model.Eventos.Select(x => new TArquivoEsocial
      {
        Id = x.Id,
        Any = _getXmlElement(x.XmlString)
      }).ToList()
    }
  }
};

public XmlDocument Sign(System.Security.Cryptography.X509Certificates.X509Certificate2 cert, string xmlString)
    {
      var doc = new XmlDocument();
      doc.PreserveWhitespace = false;
      doc.LoadXml(xmlString);

      Reference referenc = new Reference
      {
        Uri = string.Empty,
        DigestMethod = "http://www.w3.org/2001/04/xmlenc#sha256",
      };
      referenc.AddTransform(new XmlDsigEnvelopedSignatureTransform());
      referenc.AddTransform(new XmlDsigC14NTransform());
      referenc.DigestMethod = XmlSignatureExtensions.SHA256DIGEST;

      var kInfo = new KeyInfo();
      kInfo.AddClause(new KeyInfoX509Data(cert));


      var privKey   = (RSACryptoServiceProvider)cert.PrivateKey;
      var enhCsp    = new RSACryptoServiceProvider().CspKeyContainerInfo;

      var cspparams = new CspParameters(enhCsp.ProviderType, enhCsp.ProviderName, privKey.CspKeyContainerInfo.KeyContainerName);
      privKey       = new RSACryptoServiceProvider(cspparams);

      var signDoc = new SignedXml(doc)
      {
        KeyInfo = kInfo,
        SigningKey = privKey
      };
      signDoc.SignedInfo.SignatureMethod = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256";
      signDoc.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigC14NTransformUrl;
      signDoc.AddReference(referenc);


      signDoc.ComputeSignature();

      doc.DocumentElement.AppendChild(doc.ImportNode(signDoc.GetXml(), true));

      return doc;
    }

I really appreciate it if someone can shed some light on. Thank you

2 answers

1


I guess the problem must be how you are getting the private key of the certificate, to sign XML. See that you’re taking the properties ProviderType and ProviderName of the object RSACryptoServiceProvider newly created, and not the private key of the certificate:

var privKey   = (RSACryptoServiceProvider)cert.PrivateKey;
var enhCsp    = new RSACryptoServiceProvider().CspKeyContainerInfo;

var cspparams = new CspParameters(enhCsp.ProviderType,
                                  enhCsp.ProviderName,
                                  privKey.CspKeyContainerInfo.KeyContainerName);
privKey       = new RSACryptoServiceProvider(cspparams);

This may not be your current problem, but it may be a problem in the future, because when you instantiate a new class object RSACryptoServiceProvider, the default key is used (documentation), and the default key may not be the key you want to use for the signature.

Check out my other answer in Stack Overflow on the subject:

E-social. Invalid event subscription - Stack Overflow

There is an example of routine used to sign XML and also some reasons tips that may cause this invalid signature error.

See also this other answer, more recent, which is about EFD-Reinf, but is very similar to eSocial (the difference is that in EFD-Reinf the attribute reference.Uri should have content and in eSocial should be empty):

EFD-Reinf: Signature Error - A Xmldocument Context is Required for Enveloped Transformations

Another thing, the event S-2221 ("Toxicological Examination of the Professional Driver") that you are trying to send in the example, is part of the events of Occupational Health and Safety - OHS, that will only be sent from July/2019 to the companies of Group 1 (timeline), and this event was specifically included in version 2.5 of the eSocial layout, which was implemented yesterday in the Restricted Production Environment, but will only be implemented on 01/21/2019 in the Production Environment (news story).

If you are starting now in eSocial, it is best to always catch the event S-1000 ("Employer/Taxpayer/Public Body Information") first, which is the beginning of everything.

  • 1

    Thanks for the feedback, I am aware of this issue of SST, by the fact that our software is responsible only for these events.

  • I’ll check the two links you forwarded, thank you very much

  • I got it @Vicenzomartinelli. But anyway start testing with an S-1000, because I don’t think the S-2221 is even available to test yet. Let me know if you have solved the signature error.

  • I already performed the test Pedro, really the problem was in the form that was taking the information from the private key, changed the code a little and worked ok.

  • Nice @Vicenzomartinelli! If you can then mark the answer as you accept, then! ;-) See: Someone answered me and Why vote?.

0

Browser other questions tagged

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