Sample code for 30+ languages & platforms
Zig

Sign SOAP XML for New Zealand Customs Service

See more XAdES Examples

Demonstrates how to create an XAdES signed SOAP XML pertaining to the New Zealand Customs Service.

Note: This example requires Chilkat v9.5.0.96 or later.

Chilkat Zig Downloads

Zig
const std = @import("std");
const chilkat = @import("chilkat");

pub fn main(init: std.process.Init) !void {
    const alloc = init.arena.allocator();

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

    // Create the following XML to be signed:

    // <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
    //     xmlns:v1="http://customs.govt.nz/jbms/msggate/reqresp/v1">
    //     <soapenv:Header>
    //         <wsse:Security soapenv:mustUnderstand="1"
    //             xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"
    //             xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
    //             <wsu:Timestamp wsu:Id="TS-037E78514E9B9132CB16817563559151">
    //                 <wsu:Created>2023-04-17T18:32:35.913Z</wsu:Created>
    //                 <wsu:Expires>2023-04-17T19:32:35.913Z</wsu:Expires>
    //             </wsu:Timestamp>
    //         </wsse:Security>
    //     </soapenv:Header>
    //     <soapenv:Body wsu:Id="id-8"
    //         xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
    //         <v1:RequestResponse>
    //             <v1:Submitter>TEST1234</v1:Submitter>
    //             <v1:MailboxMsgId>999999</v1:MailboxMsgId>
    //         </v1:RequestResponse>
    //     </soapenv:Body>
    // </soapenv:Envelope>

    // Create a random ID like this: TS-037E78514E9B9132CB16817563559151
    const ts_id = try chilkat.StringBuilder.init();
    defer ts_id.deinit();
    ts_id.append("TS-") catch {};
    ts_id.appendRandom(16, "hex") catch {};

    // STR-037E78514E9B9132CB16817563559614
    const str_id = try chilkat.StringBuilder.init();
    defer str_id.deinit();
    str_id.append("STR-") catch {};
    str_id.appendRandom(16, "hex") catch {};

    // KI-037E78514E9B9132CB16817563559583
    const key_info_id = try chilkat.StringBuilder.init();
    defer key_info_id.deinit();
    key_info_id.append("KI-") catch {};
    key_info_id.appendRandom(16, "hex") catch {};

    // Create a date/time for the current time with this format:  2023-04-17T18:32:35.913Z
    const dt = try chilkat.DateTime.init();
    defer dt.deinit();
    dt.setFromCurrentSystemTime() catch {};

    const sb_now = try chilkat.StringBuilder.init();
    defer sb_now.deinit();
    sb_now.append(try dt.getAsTimestamp(alloc, false)) catch {};
    // If we really need the milliseconds, we can replace the "Z" with ".000Z"
    // The server will also likely accept a timestamp without milliseconds, such as 2023-04-17T18:32:35Z
    var n: i32 = sb_now.replace("Z", ".000Z");

    const sb_now_plus_one_hour = try chilkat.StringBuilder.init();
    defer sb_now_plus_one_hour.deinit();
    dt.addSeconds(3600) catch {};
    sb_now_plus_one_hour.append(try dt.getAsTimestamp(alloc, false)) catch {};
    n = sb_now_plus_one_hour.replace("Z", ".000Z");

    const xml_to_sign = try chilkat.Xml.init();
    defer xml_to_sign.deinit();
    xml_to_sign.setTag("soapenv:Envelope");
    xml_to_sign.addAttribute("xmlns:soapenv", "http://schemas.xmlsoap.org/soap/envelope/") catch {};
    xml_to_sign.addAttribute("xmlns:v1", "http://customs.govt.nz/jbms/msggate/reqresp/v1") catch {};
    xml_to_sign.updateAttrAt("soapenv:Header|wsse:Security", true, "soapenv:mustUnderstand", "1") catch {};
    xml_to_sign.updateAttrAt("soapenv:Header|wsse:Security", true, "xmlns:wsse", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd") catch {};
    xml_to_sign.updateAttrAt("soapenv:Header|wsse:Security", true, "xmlns:wsu", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd") catch {};
    xml_to_sign.updateAttrAt("soapenv:Header|wsse:Security|wsu:Timestamp", true, "wsu:Id", try ts_id.getAsString(alloc)) catch {};
    xml_to_sign.updateChildContent("soapenv:Header|wsse:Security|wsu:Timestamp|wsu:Created", try sb_now.getAsString(alloc));
    xml_to_sign.updateChildContent("soapenv:Header|wsse:Security|wsu:Timestamp|wsu:Expires", try sb_now_plus_one_hour.getAsString(alloc));
    xml_to_sign.updateAttrAt("soapenv:Body", true, "wsu:Id", "id-8") catch {};
    xml_to_sign.updateAttrAt("soapenv:Body", true, "xmlns:wsu", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd") catch {};
    xml_to_sign.updateChildContent("soapenv:Body|v1:RequestResponse|v1:Submitter", "TEST1234");
    xml_to_sign.updateChildContent("soapenv:Body|v1:RequestResponse|v1:MailboxMsgId", "999999");

    const gen = try chilkat.XmlDSigGen.init();
    defer gen.deinit();

    gen.setSigLocation("soapenv:Envelope|soapenv:Header|wsse:Security");
    gen.setSigLocationMod(0);
    gen.setSigId("SIG-037E78514E9B9132CB16817563559695");
    gen.setSigNamespacePrefix("ds");
    gen.setSigNamespaceUri("http://www.w3.org/2000/09/xmldsig#");
    gen.setSignedInfoPrefixList("soapenv v1");
    gen.setIncNamespacePrefix("ec");
    gen.setIncNamespaceUri("http://www.w3.org/2001/10/xml-exc-c14n#");
    gen.setSignedInfoCanonAlg("EXCL_C14N");
    gen.setSignedInfoDigestMethod("sha256");

    // Set the KeyInfoId before adding references..
    gen.setKeyInfoId(try key_info_id.getAsString(alloc));

    // -------- Reference 1 --------
    const xml1 = try chilkat.Xml.init();
    defer xml1.deinit();
    xml1.setTag("ds:Transforms");
    xml1.updateAttrAt("ds:Transform", true, "Algorithm", "http://www.w3.org/2001/10/xml-exc-c14n#") catch {};
    xml1.updateAttrAt("ds:Transform|ec:InclusiveNamespaces", true, "PrefixList", "wsse soapenv v1") catch {};
    xml1.updateAttrAt("ds:Transform|ec:InclusiveNamespaces", true, "xmlns:ec", "http://www.w3.org/2001/10/xml-exc-c14n#") catch {};

    gen.addSameDocRef2(try ts_id.getAsString(alloc), "sha256", xml1, "") catch {};

    // -------- Reference 2 --------
    const xml2 = try chilkat.Xml.init();
    defer xml2.deinit();
    xml2.setTag("ds:Transforms");
    xml2.updateAttrAt("ds:Transform", true, "Algorithm", "http://www.w3.org/2001/10/xml-exc-c14n#") catch {};
    xml2.updateAttrAt("ds:Transform|ec:InclusiveNamespaces", true, "PrefixList", "v1") catch {};
    xml2.updateAttrAt("ds:Transform|ec:InclusiveNamespaces", true, "xmlns:ec", "http://www.w3.org/2001/10/xml-exc-c14n#") catch {};

    gen.addSameDocRef2("id-8", "sha256", xml2, "") catch {};

    // Provide a certificate + private key. (PFX password is test123)
    const cert = try chilkat.Cert.init();
    defer cert.deinit();
    cert.loadPfxFile("qa_data/pfx/cert_test123.pfx", "test123") catch {
        std.debug.print("{s}\n", .{try cert.getLastErrorText(alloc)});
        return;
    };

    gen.setX509Cert(cert, true) catch {};

    gen.setKeyInfoType("Custom");

    // Create the custom KeyInfo XML..
    const xml_custom_key_info = try chilkat.Xml.init();
    defer xml_custom_key_info.deinit();
    xml_custom_key_info.setTag("wsse:SecurityTokenReference");
    xml_custom_key_info.addAttribute("wsu:Id", try str_id.getAsString(alloc)) catch {};
    xml_custom_key_info.updateAttrAt("wsse:KeyIdentifier", true, "EncodingType", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary") catch {};
    xml_custom_key_info.updateAttrAt("wsse:KeyIdentifier", true, "ValueType", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3") catch {};
    // Insert the single-line base64 of the signing certificate's DER
    cert.setUncommonOptions("Base64CertNoCRLF");
    xml_custom_key_info.updateChildContent("wsse:KeyIdentifier", try cert.getEncoded(alloc));

    xml_custom_key_info.setEmitXmlDecl(false);
    gen.setCustomKeyInfoXml(try xml_custom_key_info.getXml(alloc));

    // Load XML to be signed...
    const sb_xml = try chilkat.StringBuilder.init();
    defer sb_xml.deinit();
    xml_to_sign.getXmlSb(sb_xml) catch {};

    gen.setBehaviors("IndentedSignature");

    // Sign the XML...
    gen.setVerboseLogging(true);
    gen.createXmlDSigSb(sb_xml) catch {
        std.debug.print("{s}\n", .{try gen.getLastErrorText(alloc)});
        return;
    };

    // Save the signed XML to a file.
    try sb_xml.writeFile("c:/temp/qa_output/signedXml.xml", "utf-8", false);

    std.debug.print("{s}\n", .{try sb_xml.getAsString(alloc)});
}