Sample code for 30+ languages & platforms
Zig

ZATCA QR Code TLV Encoding and ECDSA Cryptographic Stamp

See more ZATCA Examples

Demonstrates how to create the TLV encoding of the QR code fields, then apply the ECDSA signature and ECDSA public key, and finally insert into the previously signed XML E-Invoice.

Note: This example requires Chilkat v9.5.0.92 or greater.

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 requires the Chilkat API to have been previously unlocked.
    // See Global Unlock Sample for sample code.

    // In Step 1, we applied a signature to an e-invoice Zakat, Tax and Customs Authority (ZATCA) of Saudi Arabia

    // This example is Step 2, where we compose the TLV encoding of the QR code, apply the ECDSA signature, and then insert into the signed XML without disturbing the signed XML.

    // Construct TLV (Tag-Length-Value) encoding of the QR data.
    // We have 5 pieces of data: Seller Name, VAT Number, Time Stamp, Invoice Total, and VAT Total.
    // For example:
    const seller_name = "Firoz Ashraf";
    const vat_number = "1234567891";

    // The timestamp in QR Code should be based on Invoice Issue Time (KSA-25) and Invoice Issue Date (BT-2).
    // It can either be in format YYYY-MM-DD'T'HH:MM:SS (for local time in KSA) or YYYY-MM-DD'T'HH:MM:SS'Z' (for UTC time or Zulu time)

    // Get the current UTC date/time in this format: YYYY-MM-DD'T'HH:MM:SS'Z'
    const dt = try chilkat.DateTime.init();
    defer dt.deinit();
    dt.setFromCurrentSystemTime() catch {};
    const time_stamp = try dt.getAsTimestamp(alloc, false);
    const invoice_total = "100.00";
    const vat_total = "15.00";

    // TLV encode into a Chilkat BinData object.
    const bd_tlv = try chilkat.BinData.init();
    defer bd_tlv.deinit();

    const charset = "utf-8";

    var tag: i32 = 1;
    bd_tlv.appendByte(tag) catch {};
    bd_tlv.appendCountedString(1, false, seller_name, charset) catch {};
    tag = tag + 1;
    // This is tag 2
    bd_tlv.appendByte(tag) catch {};
    bd_tlv.appendCountedString(1, false, vat_number, charset) catch {};
    tag = tag + 1;
    // This is tag 3
    bd_tlv.appendByte(tag) catch {};
    bd_tlv.appendCountedString(1, false, time_stamp, charset) catch {};
    tag = tag + 1;
    // This is tag 4
    bd_tlv.appendByte(tag) catch {};
    bd_tlv.appendCountedString(1, false, invoice_total, charset) catch {};
    tag = tag + 1;
    // This is tag 5
    bd_tlv.appendByte(tag) catch {};
    bd_tlv.appendCountedString(1, false, vat_total, charset) catch {};

    // ----------------------------------------------------------------------------------------------------------------------------------------------
    // For tag 6, we need the SHA256 hash from the signed XML.  This is the DigestValue as shown in the fragment of the XML Signature below:

    //     <ds:Reference Id="invoiceSignedData" URI="">
    //         <ds:Transforms>
    //             <ds:Transform Algorithm="http://www.w3.org/TR/1999/REC-xpath-19991116">
    //                 <ds:XPath>not(//ancestor-or-self::ext:UBLExtensions)</ds:XPath>
    //             </ds:Transform>
    //             <ds:Transform Algorithm="http://www.w3.org/TR/1999/REC-xpath-19991116">
    //                 <ds:XPath>not(//ancestor-or-self::cac:Signature)</ds:XPath>
    //             </ds:Transform>
    //             <ds:Transform Algorithm="http://www.w3.org/TR/1999/REC-xpath-19991116">
    //                 <ds:XPath>not(//ancestor-or-self::cac:AdditionalDocumentReference[cbc:ID='QR'])</ds:XPath>
    //             </ds:Transform>
    //             <ds:Transform Algorithm="http://www.w3.org/2006/12/xml-c14n11"/>
    //         </ds:Transforms>
    //         <ds:DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/>
    //         <ds:DigestValue>zCp+kF1qzNgXD6AhLq69/CYCklMFSXUmmVPbm4v/76U=</ds:DigestValue>
    //     </ds:Reference>

    // To get this information, we'll need to load the signed XML into a Chilkat XML object, and then access it.
    // Load the XML we previously signed...
    const signed_xml_file_path = "qa_data/zatca/testing/SignedXML.xml";
    const xml_signed = try chilkat.Xml.init();
    defer xml_signed.deinit();
    xml_signed.loadXmlFile(signed_xml_file_path) catch {
        std.debug.print("{s}\n", .{try xml_signed.getLastErrorText(alloc)});
        return;
    };

    // digestValue is a base64 string.
    const sb_digest_value = try chilkat.StringBuilder.init();
    defer sb_digest_value.deinit();
    xml_signed.getChildContentSb("ext:UBLExtensions|ext:UBLExtension|ext:ExtensionContent|sig:UBLDocumentSignatures|sac:SignatureInformation|ds:Signature|ds:SignedInfo|ds:Reference[0]|ds:DigestValue", sb_digest_value) catch {
        std.debug.print("Failed to get DigestValue from signed XML.\n", .{});
        return;
    };

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

    // Append the DigestValue base64 string to the TLV.
    tag = 6;
    bd_tlv.appendByte(tag) catch {};
    bd_tlv.appendByte(sb_digest_value.getLength()) catch {};
    bd_tlv.appendSb(sb_digest_value, "utf-8") catch {};

    // ----------------------------------------------------------------------------------------------------------------------------------------------
    // Tag 7 will contain the <ds:Signature> value from the signed XML.
    // PS> To get the XML path passed to GetChildContentSb, you can copy/paste the signed XML into Chilkat's online tool at https://tools.chilkat.io/xmlParse
    // The parsing code that is generated by the online tool will reveal the required path to the element in the XML.
    const sb_signature_value = try chilkat.StringBuilder.init();
    defer sb_signature_value.deinit();
    xml_signed.getChildContentSb("ext:UBLExtensions|ext:UBLExtension|ext:ExtensionContent|sig:UBLDocumentSignatures|sac:SignatureInformation|ds:Signature|ds:SignatureValue", sb_signature_value) catch {
        std.debug.print("Failed to get SignatureValue from signed XML.\n", .{});
        return;
    };

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

    // Append the SignatureValue base64 string to the TLV.
    tag = 7;
    bd_tlv.appendByte(tag) catch {};
    bd_tlv.appendByte(sb_signature_value.getLength()) catch {};
    bd_tlv.appendSb(sb_signature_value, "utf-8") catch {};

    // ----------------------------------------------------------------------------------------------------------------------------------------------
    // Tag 8 will contain the public key of the signing certificate.
    // The signing certificate is available within the signed XML at <ds:X509Certificate>.
    const x509_certificate = xml_signed.getChildContent(alloc, "ext:UBLExtensions|ext:UBLExtension|ext:ExtensionContent|sig:UBLDocumentSignatures|sac:SignatureInformation|ds:Signature|ds:KeyInfo|ds:X509Data|ds:X509Certificate") catch {
        std.debug.print("Failed to get X509Certificate from the signed XML.\n", .{});
        return;
    };

    const cert = try chilkat.Cert.init();
    defer cert.deinit();
    cert.setFromEncoded(x509_certificate) catch {
        std.debug.print("Failed to load signing certificate from base64.\n", .{});
        return;
    };

    // We want to get the cert's public key bytes having this ASN.1 format.
    // SEQUENCE (2 elem)
    //   SEQUENCE (2 elem)
    //     OBJECT IDENTIFIER 1.2.840.10045.2.1 ecPublicKey (ANSI X9.62 public key type)
    //     OBJECT IDENTIFIER 1.3.132.0.10 secp256k1 (SECG (Certicom) named elliptic curve)
    //   BIT STRING (520 bit) 0000010001110000110111000001111110100110101110110101111000110001110100

    // Note: The cert.GetPubKeyDer method was added in Chilkat v9.5.0.92
    const bd_pub_key = try chilkat.BinData.init();
    defer bd_pub_key.deinit();
    cert.getPubKeyDer(true, bd_pub_key) catch {
        std.debug.print("Failed to get certificate's public key.\n", .{});
        return;
    };

    // We want to add the binary bytes of the public key (not the base64 string) to the QR code.
    tag = 8;
    bd_tlv.appendByte(tag) catch {};
    bd_tlv.appendByte(bd_pub_key.getNumBytes()) catch {};
    bd_tlv.appendBd(bd_pub_key) catch {};

    // Show the public key in base64 format:
    std.debug.print("Certificate public key:\n", .{});
    std.debug.print("{s}\n", .{try bd_pub_key.getEncoded(alloc, "base64")});

    // ----------------------------------------------------------------------------------------------------------------------------------------------
    // Tag 9 will contain the signature contained in the signing certificate.

    // Note: The cert.GetPubKeyDer method was added in Chilkat v9.5.0.92
    const bd_cert_sig = try chilkat.BinData.init();
    defer bd_cert_sig.deinit();
    cert.getSignature(bd_cert_sig) catch {
        std.debug.print("Failed to get certificate's signature.\n", .{});
        return;
    };

    // We want to add the binary bytes of the signature (not the base64 string) to the QR code.
    tag = 9;
    bd_tlv.appendByte(tag) catch {};
    bd_tlv.appendByte(bd_cert_sig.getNumBytes()) catch {};
    bd_tlv.appendBd(bd_cert_sig) catch {};

    // Show the cert's signature in hex format:
    std.debug.print("Certificate signature:\n", .{});
    std.debug.print("{s}\n", .{try bd_cert_sig.getEncoded(alloc, "hex")});

    // ----------------------------------------------------------------------------------------------------------------------------------------------
    // At this point the full QR code is contained in bdTlv.
    // Get it as a base64 string
    const qr_base64 = try bd_tlv.getEncoded(alloc, "base64");
    std.debug.print("QR: {s}\n", .{qr_base64});

    // ----------------------------------------------------------------------------------------------------------------------------------------------
    // Insert the QR XML fragment into the previously signed XML -- without disturbing (invalidating) the signature.

    // We need to build and insert the following XML fragment under the
    // as a cac:AdditionalDocumentReference just before the "<cac:Signature>" opening tag.

    //    <cac:AdditionalDocumentReference>
    //         <cbc:ID>QR</cbc:ID>
    //         <cac:Attachment>
    //             <cbc:EmbeddedDocumentBinaryObject mimeCode="text/plain">BASE64_TLV_CONTENT</cbc:EmbeddedDocumentBinaryObject>
    //         </cac:Attachment>
    //    </cac:AdditionalDocumentReference>

    const xml_qr = try chilkat.Xml.init();
    defer xml_qr.deinit();
    xml_qr.setTag("cac:AdditionalDocumentReference");
    xml_qr.updateChildContent("cbc:ID", "QR");
    xml_qr.updateAttrAt("cac:Attachment|cbc:EmbeddedDocumentBinaryObject", true, "mimeCode", "text/plain") catch {};
    xml_qr.updateChildContent("cac:Attachment|cbc:EmbeddedDocumentBinaryObject", try bd_tlv.getEncoded(alloc, "base64"));

    // Load our previously signed XML into a Chilkat StringBuilder.
    // We should not load the previously signed XML into a Chilkat XML object because the XML gets loaded into an internal DOM (Document Object Model).
    // When re-emitted from the DOM, formatting can change and it would break the XML signature.
    // Therefore, we must load into a StringBuilder and insert the new fragment without disturbing the remainder.
    // The inserted fragment is ignored because the following transform was included in the XML signature reference:

    //             <ds:Transform Algorithm="http://www.w3.org/TR/1999/REC-xpath-19991116">
    //                 <ds:XPath>not(//ancestor-or-self::cac:AdditionalDocumentReference[cbc:ID='QR'])</ds:XPath>
    //             </ds:Transform>

    const sb_signed_xml = try chilkat.StringBuilder.init();
    defer sb_signed_xml.deinit();
    sb_signed_xml.loadFile(signed_xml_file_path, "utf-8") catch {
        std.debug.print("Failed to load previously signed XML file.\n", .{});
        return;
    };

    const sb_replace_str = try chilkat.StringBuilder.init();
    defer sb_replace_str.deinit();
    xml_qr.setEmitXmlDecl(false);
    xml_qr.setEmitCompact(true);
    sb_replace_str.append(try xml_qr.getXml(alloc)) catch {};
    sb_replace_str.append("<cac:Signature>") catch {};
    sb_signed_xml.replaceFirst("<cac:Signature>", try sb_replace_str.getAsString(alloc)) catch {
        std.debug.print("Did not find <cac:Signature> in the signed XML\n", .{});
        return;
    };

    // Save the updated signed XML.
    try sb_signed_xml.writeFile("qa_output/signedXML_withQR.xml", "utf-8", false);

    // ----------------------------------------
    // Verify the updated signed XML to make sure we didn't invalidate the signature...
    const verifier = try chilkat.XmlDSig.init();
    defer verifier.deinit();
    verifier.loadSignatureSb(sb_signed_xml) catch {
        std.debug.print("{s}\n", .{try verifier.getLastErrorText(alloc)});
        return;
    };

    // ---------------- This is important -----------------------------------------
    // Starting in Chilkat v9.5.0.92, specify "ZATCA" in uncommon options
    // to validate signed XML according to ZATCA needs.
    // ----------------------------------------------------------------------------
    verifier.setUncommonOptions("ZATCA");

    const num_sigs = verifier.getNumSignatures();
    var verify_idx: i32 = 0;
    while (verify_idx < num_sigs) {
        verifier.setSelector(verify_idx);
        verifier.verifySignature(true) catch {
            std.debug.print("{s}\n", .{try verifier.getLastErrorText(alloc)});
            return;
        };

        verify_idx = verify_idx + 1;
    }

    std.debug.print("All signatures were successfully verified.\n", .{});
}