EldoS | Feel safer!

Software components for data protection, secure storage and transfer

Generete Digestvalue, x509Certificate and signaturevalue

Also by EldoS: CallbackProcess
A component to control process creation and termination in Windows and .NET applications.
#6020
Posted: 04/24/2008 15:51:35
by Gabriel Herdt (Standard support level)
Joined: 04/09/2008
Posts: 37

I making one similiar code. My code is ok? Please check to me.

Code
function TRDmConBas.Assinar2(Xml:WideString; iQtdNfe: Integer): WideString;
var
  Signer: TElXMLSigner;
  HMACKeyData: TElXMLKeyInfoHMACData;
  RSAKeyData: TElXMLKeyInfoRSAData;
  X509KeyData: TElXMLKeyInfoX509Data;
  Cert: TElX509Certificate;
  SigNode, Nodetest: TElXMLDOMNode;
  Ref: TElXMLReference;
  Refs: TElXMLReferenceList;
  Elementos : ElXMLDOMElement;
  Document : ElXMLDOMDocument;
  NodeSet : ElXMLNodeSet;
  S: WideString;
  i : integer;
begin
inherited;
  HMACKeyData := nil;
  RSAKeyData := nil;
  X509KeyData := nil;
  Ref := nil;
  Refs := TElXMLReferenceList.Create;
  i := 1;
  try

    Ref := TElXMLReference.Create;

    FXMLDocument := TElXMLDOMDocument.Create;
    Elementos := ParseElementFromXMLString(Xml,FXMLDocument);
    FXMLDocument.AppendChild(Elementos);
    Ref.TransformChain.Add(TElXMLEnvelopedSignatureTransform.Create);
    Ref.TransformChain.Add(TElXMLC14NTransform.Create);


    While i <= iQtdNfe do Begin

      //teste
      FXMLDocument.DocumentElement.ChildNodes.Item[i].FindNode('infNFe').Attributes.GetNamedItem('Id').NodeValue;
      Ref.URINode := FXMLDocument.DocumentElement.ChildNodes.Item[i].FindNode('infNFe');
      Ref.URI := '#'+ FXMLDocument.DocumentElement.FindNode('NFe').FindNode('infNFe').Attributes.GetNamedItem('Id').NodeValue;
      //teste

      //Ref.URI := '#NFe'+Uri;

      Refs.Add(Ref);
      //if True then begin
      Signer := TElXMLSigner.Create(Self);

        try

          Signer.SignatureType := xstEnveloped;
          Signer.CanonicalizationMethod := xcmCanon;
          Signer.SignatureMethodType := xmtSig;
          Signer.SignatureMethod := xsmRSA_SHA1;
          Signer.MACMethod := xmmHMAC_SHA1;
          Signer.References := Refs;
          Signer.IncludeKey := True;

          //Signer.OnFormatElement := FormatElement; //Formata o XML
          //Signer.OnFormatText := FormatText; //Formata o XML

           Cert := ElWinCertStorage.Certificates[(Parametro.NR_ITECER-1)];

          //ate aki ok
          if Assigned(Cert) and Cert.PrivateKeyExists then
          begin
            X509KeyData := TElXMLKeyInfoX509Data.Create(False);
            X509KeyData.IncludeDataParams := [xkidX509Certificate, xkidX509CRL];
            X509KeyData.IncludeKeyValue := False;
            X509KeyData.Certificate := Cert;
            Signer.KeyData := X509KeyData;
          end;

          Signer.UpdateReferencesDigest;

          if True then begin
            Signer.Sign;

            //SigNode := FXMLDocument.DocumentElement.FindNode('NFe');
            //teste
            SigNode := FXMLDocument.DocumentElement.ChildNodes.Item[i];

            //teste
            if SigNode is TElXMLDOMDocument then
            SigNode := TElXMLDOMDocument(SigNode).DocumentElement;

            try
              // If the signature type is enveloping, then the signature is placed into the passed node and the contents of the node are moved to inside of the signature.
              // If the signature type is enveloped, the signature is placed as a child of the passed node.
              Signer.Save(SigNode);
            except
              on E: Exception do
                raise EElXMLError.CreateFmt('Falha ao salvar os dados da assinatura. (%s)', [E.Message]);
              end;
          end;
        finally
          FreeAndNil(Signer);
          FreeAndNil(HMACKeyData);
          FreeAndNil(RSAKeyData);
          FreeAndNil(X509KeyData);
        end;
        i := (i+1);
      end;
      SalvaArq('C:\Documents and Settings\user\Desktop\envNfeAss1.xml');
  finally
   FreeAndNil(Refs);
  end;
end;


My validator schema xml return:

PARSER XML: OK
SCHEMA: The element 'SignedInfo' in namespace 'http://www.w3.org/2000/09/xmldsig#' has invalid child element 'Reference' in namespace 'http://www.w3.org/2000/09/xmldsig#'.



Gabriel Herdt
Consystec
#6021
Posted: 04/24/2008 16:13:16
by Dmytro Bogatskyy (EldoS Corp.)

You need to create and fill Refs and Ref in the loop too.
And also you should check if FXMLDocument.DocumentElement.ChildNodes.Item[i].LocalName = "NFe" then sign node.
#6183
Posted: 05/08/2008 18:44:22
by Andresa Braz (Basic support level)
Joined: 05/08/2008
Posts: 5

I have a similar problem to Gabriel´s problem. How can I don´t show this sentences in bold face?. My validator schema returns "The element 'SignedInfo' in namespace 'http://www.w3.org/2000/0­9/xmldsig#' has invalid child element 'Reference' in namespace 'http://www.w3.org/2000/0­9/xmldsig#'"


I use the exemple of the Gabriel´s code.

Code
<Signature xmlns="http://www.w3.org/2000/09/xmldsig#" [B]xmlns:ds="http://www.w3.org/2000/09/xmldsig#"[/B]>
<SignedInfo>
  <CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315" />
  <SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1" />
<Reference URI="#NFe31080465105041000198550030000000870000000876">
<Transforms>
  <Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature" />
  </Transforms>
  <DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" />
  <DigestValue>qA+pXMfOtl7BABmyGyvNsvXLduw=</DigestValue>
  </Reference>
  </SignedInfo>
  <SignatureValue>FkDYomjjr7t78GvbBsjelvVGjceVw0rWPrZ7PcotcYl9BKzfrUv1mF5lt/9HPaQy 3lqeLMHnyeFDkQuax+8pllcxLtY1kATumjrsv0EnHr6/gbLshlG/hrZKoTU8dhX0 fg4ZmXdAh8VjoZ6A+1R1goFJ+vLVjzkbD6AIHbhDwgc=</SignatureValue>
<KeyInfo>
[B]<KeyValue>
<RSAKeyValue>
  <Modulus>rzo0dqHHWwN6AZmoTZWT+UIDws8F8zAaQILNeVQa08oTbneP5kqm6x9WoT8/XhUb EQceDzpFVIeyFGtdAI6l72gMzyqlG0aMiV4qL60Rz4m6y90660DfrcXw2T/k3zXk s59mnCVUE+aVBcbgTrlB4fImHf0qS+LwLrxIzmKZfmc=</Modulus>
  <Exponent>AQAB</Exponent>
  </RSAKeyValue>
  </KeyValue>[/B] <X509Data>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kby1hbHRAcHJvY2VyZ3MucnMuZ292LmJyMCAG A1UdJQEB/wQWMBQGCCsGAQUFBwMCBggrBgEFBQcDBDAYBgNVHR8BAQAEDjAMMAqg BKAChgCBAgB/MA0GCSqGSIb3DQEBBQUAA4IBAQA5skKrfEv5tY4ct7eSWwKV4VpW a4apkjQYlOxMYOm9MZuKhYXAKvTiYPPL4WwqS20Cn6hd3CeEl8eICUKfVhMSIoHA YGv6KjA6B2R4ZU66P0oljdfKtkXAqLX+04y8CiEfDNx0g/+gYtArhx+rFW/zNSEZ l7sWNGJQ7TRe/d2+hejYFoY+wcUEYOHrSrnEGSlkax5E2HcJBDSE9fGGuOrnAztd 5w4m9VuKwdRyK0pqnPPxuhrClbRdspnAnLjif5K7ggjSl+C7LZbkaWVrH1I8GzMR yrmwLBbQw6GftKlWPeZhpC4JJixmcP+J3jv2dNN88vitIuQxG1WfNd+FLl41</X509Certificate>
  </X509Data>
  </KeyInfo>
  </Signature>

#6187
Posted: 05/09/2008 04:53:25
by Dmytro Bogatskyy (EldoS Corp.)

Quote
My validator schema returns...

What xml validator are you using? And what schema does it use?
The correct one is here:
http://www.w3.org/TR/xmldsig-core/#sec-Schema

Quote
How can I don´t show this sentences in bold face?

Insert following two lines:
Code
X509KeyData.IncludeKeyValue := False;
...
Signer.Sign();
...
Signer.Signature.SignaturePrefix := '#default'; // default is "#default ds"
#6198
Posted: 05/09/2008 20:27:18
by Andresa Braz (Basic support level)
Joined: 05/08/2008
Posts: 5

I made my own validator using a .xsd Schema and acording to them i think this is not necessary.

I think there are something wrong with my "X509KeyData" coz I don´t have an "IncludeKeyVal­ue" property. Or what I´m doing wrong?? My X509KeyData is a "TElXMLKeyInfoX509Data".
#6199
Posted: 05/10/2008 04:59:51
by Dmytro Bogatskyy (EldoS Corp.)

Quote
I think there are something wrong with my "X509KeyData" coz I don´t have an "IncludeKeyValue" property. Or what I´m doing wrong?? My X509KeyData is a "TElXMLKeyInfoX509Data".

Please, update to the latest release. This property was added not so long time ago.
#6200
Posted: 05/10/2008 20:54:29
by Andresa Braz (Basic support level)
Joined: 05/08/2008
Posts: 5

I update my component to last release, but when I try to execute my program I receive from Delphi 7 a dialog box asking me about the correct source path of "SBXMLCore.pas". I find here and I don´t have this file.

I try to ignore but doesn´t work.

This error occurs in this line
Code
Ref.URINode:=FXMLDocument.DocumentElement.FindNode('NFe').FindNode('infNFe');
#6201
Posted: 05/11/2008 09:20:23
by Dmytro Bogatskyy (EldoS Corp.)

Quote
I receive from Delphi 7 a dialog box asking me about the correct source path of "SBXMLCore.pas"

Most likely there's some exception that the IDE wants to report.
For example:
1. FXMLDocument.DocumentElement could be null if xml document not loaded
2. FXMLDocument.DocumentElement.FindNode('NFe') could be null if node not found
#6216
Posted: 05/12/2008 19:19:25
by Andresa Braz (Basic support level)
Joined: 05/08/2008
Posts: 5

My code is OK?? I Think "ParseElementFromXMLString" doesn´t work correctly in my computer.

Code
FUNCTION TfrmMain.Executa_Assinatura(XML, Uri : WideString): WideString;
var
  Signer        : TElXMLSigner;
  HMACKeyData   : TElXMLKeyInfoHMACData;
  RSAKeyData    : TElXMLKeyInfoRSAData;
  X509KeyData   : TElXMLKeyInfoX509Data;
  Cert          : TElX509Certificate;
  SigNode       : TElXMLDOMNode;
  Ref           : TElXMLReference;
  Refs          : TElXMLReferenceList;
  Elementos     : ElXMLDOMElement;
  Document      : ElXMLDOMDocument;
  I             : Integer;
begin
  HMACKeyData:=Nil;
  RSAKeyData:=Nil;
  X509KeyData:=Nil;
  Ref:=Nil;
  Refs:=TElXMLReferenceList.Create;

  Try
    Ref:=TElXMLReference.Create;

    FXMLDocument:=TElXMLDOMDocument.Create;
    Elementos:=ParseElementFromXMLString(XML, FXMLDocument);

    FXMLDocument.AppendChild(Elementos);

    Ref.URINode:=FXMLDocument.DocumentElement.FindNode('NFe').FindNode('infNFe');

    Ref.URI:='#NFe'+Uri;
    Ref.TransformChain.Add(TElXMLEnvelopedSignatureTransform.Create);
    Ref.TransformChain.Add(TElXMLC14NTransform.Create);

    Refs.Add(Ref);

    Signer:=TElXMLSigner.Create(Self);

    Try
      Signer.SignatureType:=xstEnveloped;
      Signer.CanonicalizationMethod:=xcmCanon;
      Signer.SignatureMethodType:=xmtSig;
      Signer.SignatureMethod:=xsmRSA_SHA1;
      Signer.MACMethod:=xmmHMAC_SHA1;
      Signer.References:=Refs;
      Signer.IncludeKey:=True;

      If (frmSelWinCert.ShowModal = mrOK) Then
        Cert:=frmSelWinCert.Certificate;

      If Assigned(Cert) and Cert.PrivateKeyExists Then Begin
        X509KeyData:= TElXMLKeyInfoX509Data.Create(False);
        X509KeyData.IncludeDataParams:=[xkidX509Certificate, xkidX509CRL];
        X509KeyData.IncludeKeyValue:=False;
        X509KeyData.Certificate:=Cert;
        Signer.KeyData:=X509KeyData;
      end;

      Signer.UpdateReferencesDigest;

      If True then begin
        Signer.Sign;

        SigNode := FXMLDocument.DocumentElement.FindNode('NFe');

        If SigNode is TElXMLDOMDocument Then
          SigNode := TElXMLDOMDocument(SigNode).DocumentElement;

        Try
          Signer.Save(SigNode);

          FXMLDocument.OuterXML;
          signode.OuterXML;

          SaveArquivoXMLAssinado('C:\Teste\'+Uri+'-nfe.xml')

        except
          on E: Exception do
            raise EElXMLError.CreateFmt('Falha ao salvar os dados da assinatura. (%s)', [E.Message]);
        end;
      end;
    finally
      FreeAndNil(Signer);
      FreeAndNil(HMACKeyData);
      FreeAndNil(RSAKeyData);
      FreeAndNil(X509KeyData);
    end;
  finally
    FreeAndNil(Refs);
  end;
end;



I send to my function a widestring like that:
Code
<NFe xmlns="http://www.portalfiscal.inf.br/nfe"><infNFe versao="1.10" Id="NFe31080465105041000198550030000000870000000876"><ide><cUF>31</cUF><cNF>000000087</cNF><natOp>VENDA COMBUSTIVEL OU LUBRIFIC. DEST. CONS.OU USUARIO FINAL</natOp><indPag>1</indPag><mod>55</mod><serie>3</serie><nNF>87</nNF><dEmi>2008-04-02</dEmi><dSaiEnt>2008-04-02</dSaiEnt><tpNF>1</tpNF><cMunFG>3106705</cMunFG><tpImp>1</tpImp><tpEmis>1</tpEmis><cDV>6</cDV><tpAmb>1</tpAmb><finNFe>1</finNFe><procEmi>0</procEmi><verProc>ERP Globus</verProc></ide><emit><CNPJ>65105041000198</CNPJ><xNome>PETROVILA COMBUSTIVEIS LTDA</xNome><xFant>PETROVILA COMBUSTIVEIS</xFant><enderEmit><xLgr>RUA JOAO VALERIO</xLgr><nro>177</nro><xBairro>VILA BOA ESPERANCA</xBairro><cMun>3106705</cMun><xMun>BETIM</xMun><UF>MG</UF><CEP>32680290</CEP><cPais>1058</cPais><xPais>BRASIL</xPais></enderEmit><IE>0676704090028</IE></emit><dest><CNPJ>16629693000116</CNPJ><xNome>INTEGRAL ENGENHARIA LTDA</xNome><enderDest><xLgr>AVENIDA ASSIS CHATEAUBRIAND</xLgr><nro>244</nro><xBairro>FLORESTA</xBairro><cMun>3106200</cMun><xMun>BELO HORIZONTE</xMun><UF>MG</UF><CEP>30150100</CEP><cPais>1058</cPais><xPais>BRASIL</xPais></enderDest><IE>0621222640006</IE></dest><det nItem="1"><prod><cProd>01000010</cProd><cEAN>01000010</cEAN><xProd>OLEO DIESEL INTERIOR S2000 B2</xProd><genero>0</genero><CFOP>5656</CFOP><uCom>2</uCom><qCom>5000.0000</qCom><vUnCom>1.6944</vUnCom><vProd>8472.00</vProd><cEANTrib>01000010</cEANTrib><uTrib>2</uTrib><qTrib>5000.0000</qTrib><vUnTrib>1.6944</vUnTrib></prod><imposto><ICMS><ICMS60><orig>0</orig><CST>60</CST><vBCST>9385.00</vBCST><vICMSST>1126.20</vICMSST></ICMS60></ICMS><PIS><PISAliq><CST>01</CST><vBC>0</vBC><pPIS>0</pPIS><vPIS>0</vPIS></PISAliq></PIS><COFINS><COFINSAliq><CST>01</CST><vBC>0</vBC><pCOFINS>0</pCOFINS><vCOFINS>0</vCOFINS></COFINSAliq></COFINS></imposto></det><total><ICMSTot><vBC>0.00</vBC><vICMS>0.00</vICMS><vBCST>9385.00</vBCST><vST>1126.20</vST><vProd>8472.00</vProd><vFrete>0.00</vFrete><vSeg>0.00</vSeg><vDesc>0</vDesc><vII>0</vII><vIPI>0</vIPI><vPIS>0</vPIS><vCOFINS>0</vCOFINS><vOutro>0.00</vOutro><vNF>8472.00</vNF></ICMSTot></total><transp><modFrete>0</modFrete></transp></infNFe></NFe>
#6220
Posted: 05/13/2008 05:01:45
by Dmytro Bogatskyy (EldoS Corp.)

Quote
I Think "ParseElementFromXMLString" doesn´t work correctly in my computer.

What error are you getting?

If exception at line:
Ref.URINode:=FXMLDocument.DocumentElement.FindNode('NFe').FindNode('infNFe');

It is because, you have following structure:
NFe - this is DocumentElement!
- infNFe

So, FXMLDocument.DocumentElement.FindNode('NFe') returns null for you.
In your case you should use:
Ref.URINode:=FXMLDocument.DocumentElement.FindNode('infNFe');
Also by EldoS: RawDisk
Access locked and protected files in Windows, read and write disks and partitions and more.

Reply

Statistics

Topic viewed 61057 times

Number of guests: 1, registered members: 0, in total hidden: 0




|

Back to top

As of July 15, 2016 EldoS Corporation will operate as a division of /n software inc. For more information, please read the announcement.

Got it!