Sample code for 30+ languages & platforms
Lua Requires Chilkat v9.5.0.90+

Add EncapsulatedTimestamp to Already-Signed XML

See more XML Digital Signatures Examples

Demonstrates how to add an EncapsulatedTimestamp to an existing XML signature.

Chilkat Lua Downloads

Lua
local chilkat = require("chilkat")

-- This example requires the Chilkat API to have been previously unlocked.
-- See Global Unlock Sample for sample code.

-- Note: We cannot load the already-signed XML into a Chilkat XML object because it would re-format the XML when re-emitted.
-- (i.e. indentation and whitespace could change, and it would invalidate the existing signature.)
-- We must use a StringBuilder.
local sbXml = chilkat.StringBuilder.new()
local success = sbXml:load_file("qa_data/xml_dsig_valid_samples/encapsulatedTimestamp_not_yet_added.xml", "utf-8")
if not success then
    print("Failed to load the XML file.")
    return
end

local dsig = chilkat.XmlDSig.new()
success = dsig:load_signature_sb(sbXml)
if not success then
    print(dsig.last_error_text)
    return
end

if dsig:has_encapsulated_time_stamp() then
    print("This signed XML already has an EncapsulatedTimeStamp")
    return
end

-- Specify the timestamping authority URL
local json = chilkat.JsonObject.new()
json:update_string("timestampToken.tsaUrl", "http://timestamp.digicert.com")
json:update_bool("timestampToken.requestTsaCert", true)

-- Call AddEncapsulatedTimeStamp to add the EncapsulatedTimeStamp to the signature.
-- Note: If the signed XML contains multiple signatures, the signature modified is the one
-- indicated by the dsig.Selector property.
local sbOut = chilkat.StringBuilder.new()
success = dsig:add_encapsulated_time_stamp(json, sbOut)
if not success then
    print(dsig.last_error_text)
    return
end

sbOut:write_file("qa_output/addedEncapsulatedTimeStamp.xml", "utf-8", false)

-- The EncapsulatedTimeStamp can be validated when validating the signature by adding the VerifyEncapsulatedTimeStamp
-- keyword to UncommonOptions.  See here:

-- ----------------------------------------
-- Verify the signatures we just produced...
local verifier = chilkat.XmlDSig.new()
success = verifier:load_signature_sb(sbOut)
if not success then
    print(verifier.last_error_text)
    return
end

-- Add "VerifyEncapsulatedTimeStamp" to the UncommonOptions to also verify any EncapsulatedTimeStamps
verifier.uncommon_options = "VerifyEncapsulatedTimeStamp"

local numSigs = verifier.num_signatures
local verifyIdx = 0
while verifyIdx < numSigs do
    verifier.selector = verifyIdx
    local verified = verifier:verify_signature(true)
    if not verified then
        print(verifier.last_error_text)
        return
    end

    verifyIdx = verifyIdx + 1
end

print("All signatures were successfully verified.")