XmlDSigSignXml

Ukázka podepsání XML souboru

Popis

Skript načte (nepodepsaný) XML soubor a podepíše jej algoritmem HMAC-SHA1.
declare function XmlDSigCreate dll "ScriptEx" (string): integer
declare procedure XmlDSigFree dll "ScriptEx" (var integer)

declare function XmlDSigGetStringProp dll "ScriptEx" (integer, string): string
declare procedure XmlDSigSetStringProp dll "ScriptEx" (integer, string, string)

declare function XmlDSigAddSameDocumentReference dll "ScriptEx" (integer, string, string, string): integer
declare procedure XmlDSigSign dll "ScriptEx" (integer)

declare function LoadBase64FromFile dll "ActualDocument" (string): string
declare function SaveBase64ToFile dll "ActualDocument" (string, string): integer

declare function LastErrorGetCode dll "ScriptEx" (): integer
declare function LastErrorGetMessage dll "ScriptEx" (): string

script XmlDSigSignXml(): boolean
var
  Base64: string
  XmlDSig: integer
begin
  /*
  <?xml version="1.0" encoding="windows-1250"?>
  <root>
    <text lang="en">Lorem ipsum dolor sit amet, consectetuer adipiscing elit</text>
    <text lang="cs">Příliš žluťoučký kůň úpěl ďábelské ódy</text>
  </root>
  */
  Base64 := LoadBase64FromFile("c:\Temp\Unsigned.xml")

  XmlDSig := XmlDSigCreate("TXmlDSig")
  XmlDSigSetStringProp(XmlDSig, "Base64", Base64)

  XmlDSigSetStringProp(XmlDSig, "HmacKey", "U2VjcmV0S2V5")
  XmlDSigSetStringProp(XmlDSig, "CanonicalizationMethod", "C14N")
  XmlDSigSetStringProp(XmlDSig, "SignatureDigestMethod", "SHA1")
  XmlDSigSetStringProp(XmlDSig, "SignatureParentPath", "/root")

  XmlDSigAddSameDocumentReference(XmlDSig, "", "SHA1", "C14N")
  XmlDSigSign(XmlDSig)

  result := LastErrorGetCode() = 0

  if result then
    Base64 := XmlDSigGetStringProp(XmlDSig, "Base64")
    write(Base64)

    /*
    <?xml version="1.0" encoding="windows-1250"?>
    <root>
      <text lang="en">Lorem ipsum dolor sit amet, consectetuer adipiscing elit</text>
      <text lang="cs">Příliš žluťoučký kůň úpěl ďábelské ódy</text>
      <ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
        <ds:SignedInfo>
          <ds:CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"/>
          <ds:SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#hmac-sha1"/>
          <ds:Reference URI="">
            <ds:Transforms>
              <ds:Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"/>
              <ds:Transform Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"/>
            </ds:Transforms>
            <ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
            <ds:DigestValue>1npPjuhgOGWrwfXcEGdxgJlHbHI=</ds:DigestValue>
          </ds:Reference>
        </ds:SignedInfo>
        <ds:SignatureValue>rHIBDwy0DEsl0JnBtHJEYiQdhAI=</ds:SignatureValue>
      </ds:Signature>
    </root>
    */
    SaveBase64ToFile("c:\Temp\Signed.xml", Base64)
  else
    write(LastErrorGetMessage())
  end

  XmlDSigFree(XmlDSig)
end