Create a detached signature using a HMAC key

In the example, an XML document ("MyDocument.xml") is loaded and signed with a HMAC key.

You can use the sample content provided in XML document (unsigned) for the purpose of testing the code. Copy the content to a file named "MyDocument.xml" in a directory where you test the sample code.

IMPORT xml

MAIN
  DEFINE doc xml.DomDocument
  DEFINE sig xml.Signature
  DEFINE key xml.CryptoKey
  DEFINE index INTEGER
  # Create DomDocument object
  LET doc = xml.DomDocument.Create()
  # Notice that whitespaces are significant in cryptography, 
  # therefore it is recommended that you remove unnecessary ones 
  CALL doc.setFeature("whitespace-in-element-content",FALSE)
  TRY
    # Load document to be signed
    CALL doc.load("MyDocument.xml")
    # Create HMAC key
    LET key = xml.CryptoKey.Create("http://www.w3.org/2000/09/xmldsig#hmac-sha1")
    CALL key.setKey("secretpassword")
     # Create signature object with the key to use
    LET sig = xml.Signature.Create()
    CALL sig.setKey(key)
    # Set XML node to be signed. In our case, the node with attribute
    # 'xml:id="code"'
    LET index = sig.createReference("#code",
      "http://www.w3.org/2000/09/xmldsig#sha1")
    # Set canonicalization method on the XML fragment to be signed.
    CALL sig.appendReferenceTransformation(index,
      "http://www.w3.org/2001/10/xml-exc-c14n#")
    # Compute detached signature
    CALL sig.compute(doc)
    # Retrieve signature document
    LET doc=sig.getDocument()
    # Save signature on disk
    CALL doc.setFeature("format-pretty-print",TRUE)
    CALL doc.save("MyDocumentDetachedSignature.xml")
  CATCH
    DISPLAY "Unable to create a detached signature :",status
  END TRY
END MAIN

All keys or certificates in PEM or DER format were created with the OpenSSL tool. For information on how the OpenSSL tool works, refer to the OpenSSL documentation.