Chilkat Examples

ChilkatHOME.NET Core C#Android™AutoItCC#C++Chilkat2-PythonCkPythonClassic ASPDataFlexDelphi ActiveXDelphi DLLGoJavaLianjaMono C#Node.jsObjective-CPHP ActiveXPHP ExtensionPerlPowerBuilderPowerShellPureBasicRubySQL ServerSwift 2Swift 3,4,5...TclUnicode CUnicode C++VB.NETVBScriptVisual Basic 6.0Visual FoxProXojo Plugin

C Web API Examples

Primary Categories

ABN AMRO
AWS Secrets Manager
AWS Security Token Service
AWS Translate
Activix CRM
Adyen
Alibaba Cloud OSS
Amazon Cognito
Amazon DynamoDB
Amazon MWS
Amazon Pay
Amazon Rekognition
Amazon SP-API
Amazon Voice ID
Aruba Fatturazione
Azure Maps
Azure Monitor
Azure OAuth2
Azure Storage Accounts
Backblaze S3
Banco Inter
Belgian eHealth Platform
Bitfinex v2 REST
Bluzone
BrickLink
Bunny CDN
CallRail
CardConnect
Cerved
ClickBank
Clickatell
Cloudfare
Constant Contact
DocuSign
Duo Auth MFA
ETrade
Ecwid
Egypt ITIDA
Egypt eReceipt
Etsy
Facebook
Faire
Frame.io
GeoOp
GetHarvest
Global Payments
Google People
Google Search Console
Google Translate
Google Vision
Hungary NAV Invoicing
IBM Text to Speech
Ibanity
IntakeQ
JCC Cyprus
Jira
Lightspeed
MYOB
Magento
Mailgun
Malaysia MyInvois

Mastercard
MedTunnel
MercadoLibre
MessageMedia
Microsoft Calendar
Microsoft Group
Microsoft Tasks and Plans
Microsoft Teams
Moody's
Okta OAuth/OIDC
OneLogin OIDC
OneNote
OpenAI ChatGPT
PRODA
PayPal
Paynow.pl
Peoplevox
Populi
QuickBooks
Rabobank
Refinitiv
Royal Mail OBA
SCiS Schools Catalogue
SII Chile
SMSAPI
SOAP finkok.com
Salesforce
SendGrid
Shippo
Shopify
Shopware
Shopware 6
SimpleTexting
Square
Stripe
SugarCRM
TicketBAI
TikTok Shop
Trello
Twilio
Twitter API v2
Twitter v1
UPS
UniPin
VoiceBase
Vonage
WaTrend
Walmart v3
Wasabi
WhatsApp
WiX
WooCommerce
WordPress
Xero
Yahoo Mail
Yapily
Yousign
ZATCA
Zendesk
Zoom
_Miscellaneous_
eBay
effectconnect
hacienda.go.cr

 

 

 

(C) 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 C/C++ Library Downloads

MS Visual C/C++

Linux/CentOS C/C++

Alpine Linux C/C++

MAC OS X C/C++

armhf/aarch64 C/C++

C++ Builder

iOS C/C++

Android C/C++

Solaris C/C++

MinGW C/C++

#include <C_CkDateTime.h>
#include <C_CkBinData.h>
#include <C_CkXml.h>
#include <C_CkStringBuilder.h>
#include <C_CkCert.h>
#include <C_CkXmlDSig.h>

void ChilkatSample(void)
    {
    BOOL success;
    const char *sellerName;
    const char *vatNumber;
    HCkDateTime dt;
    const char *timeStamp;
    const char *invoiceTotal;
    const char *vatTotal;
    HCkBinData bdTlv;
    const char *charset;
    int tag;
    const char *signedXmlFilePath;
    HCkXml xmlSigned;
    HCkStringBuilder sbDigestValue;
    HCkStringBuilder sbSignatureValue;
    const char *x509Certificate;
    HCkCert cert;
    HCkBinData bdPubKey;
    HCkBinData bdCertSig;
    const char *qr_base64;
    HCkXml xmlQR;
    HCkStringBuilder sbSignedXml;
    HCkStringBuilder sbReplaceStr;
    HCkXmlDSig verifier;
    int numSigs;
    int verifyIdx;
    BOOL verified;

    // 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:
    sellerName = "Firoz Ashraf";
    vatNumber = "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'
    dt = CkDateTime_Create();
    CkDateTime_SetFromCurrentSystemTime(dt);
    timeStamp = CkDateTime_getAsTimestamp(dt,FALSE);
    invoiceTotal = "100.00";
    vatTotal = "15.00";

    // TLV encode into a Chilkat BinData object.
    bdTlv = CkBinData_Create();

    charset = "utf-8";

    tag = 1;
    CkBinData_AppendByte(bdTlv,tag);
    CkBinData_AppendCountedString(bdTlv,1,FALSE,sellerName,charset);
    tag = tag + 1;
    // This is tag 2
    CkBinData_AppendByte(bdTlv,tag);
    CkBinData_AppendCountedString(bdTlv,1,FALSE,vatNumber,charset);
    tag = tag + 1;
    // This is tag 3
    CkBinData_AppendByte(bdTlv,tag);
    CkBinData_AppendCountedString(bdTlv,1,FALSE,timeStamp,charset);
    tag = tag + 1;
    // This is tag 4
    CkBinData_AppendByte(bdTlv,tag);
    CkBinData_AppendCountedString(bdTlv,1,FALSE,invoiceTotal,charset);
    tag = tag + 1;
    // This is tag 5
    CkBinData_AppendByte(bdTlv,tag);
    CkBinData_AppendCountedString(bdTlv,1,FALSE,vatTotal,charset);

    // ----------------------------------------------------------------------------------------------------------------------------------------------
    // 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...
    signedXmlFilePath = "qa_data/zatca/testing/SignedXML.xml";
    xmlSigned = CkXml_Create();
    success = CkXml_LoadXmlFile(xmlSigned,signedXmlFilePath);
    if (success == FALSE) {
        printf("%s\n",CkXml_lastErrorText(xmlSigned));
        CkDateTime_Dispose(dt);
        CkBinData_Dispose(bdTlv);
        CkXml_Dispose(xmlSigned);
        return;
    }

    // digestValue is a base64 string.
    sbDigestValue = CkStringBuilder_Create();
    success = CkXml_GetChildContentSb(xmlSigned,"ext:UBLExtensions|ext:UBLExtension|ext:ExtensionContent|sig:UBLDocumentSignatures|sac:SignatureInformation|ds:Signature|ds:SignedInfo|ds:Reference[0]|ds:DigestValue",sbDigestValue);
    if (success == FALSE) {
        printf("Failed to get DigestValue from signed XML.\n");
        CkDateTime_Dispose(dt);
        CkBinData_Dispose(bdTlv);
        CkXml_Dispose(xmlSigned);
        CkStringBuilder_Dispose(sbDigestValue);
        return;
    }

    printf("DigestValue = %s\n",CkStringBuilder_getAsString(sbDigestValue));

    // Append the DigestValue base64 string to the TLV.
    tag = 6;
    CkBinData_AppendByte(bdTlv,tag);
    CkBinData_AppendByte(bdTlv,CkStringBuilder_getLength(sbDigestValue));
    CkBinData_AppendSb(bdTlv,sbDigestValue,"utf-8");

    // ----------------------------------------------------------------------------------------------------------------------------------------------
    // 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.
    sbSignatureValue = CkStringBuilder_Create();
    success = CkXml_GetChildContentSb(xmlSigned,"ext:UBLExtensions|ext:UBLExtension|ext:ExtensionContent|sig:UBLDocumentSignatures|sac:SignatureInformation|ds:Signature|ds:SignatureValue",sbSignatureValue);
    if (success == FALSE) {
        printf("Failed to get SignatureValue from signed XML.\n");
        CkDateTime_Dispose(dt);
        CkBinData_Dispose(bdTlv);
        CkXml_Dispose(xmlSigned);
        CkStringBuilder_Dispose(sbDigestValue);
        CkStringBuilder_Dispose(sbSignatureValue);
        return;
    }

    printf("SignatureValue = %s\n",CkStringBuilder_getAsString(sbSignatureValue));

    // Append the SignatureValue base64 string to the TLV.
    tag = 7;
    CkBinData_AppendByte(bdTlv,tag);
    CkBinData_AppendByte(bdTlv,CkStringBuilder_getLength(sbSignatureValue));
    CkBinData_AppendSb(bdTlv,sbSignatureValue,"utf-8");

    // ----------------------------------------------------------------------------------------------------------------------------------------------
    // Tag 8 will contain the public key of the signing certificate.
    // The signing certificate is available within the signed XML at <ds:X509Certificate>.
    x509Certificate = CkXml_getChildContent(xmlSigned,"ext:UBLExtensions|ext:UBLExtension|ext:ExtensionContent|sig:UBLDocumentSignatures|sac:SignatureInformation|ds:Signature|ds:KeyInfo|ds:X509Data|ds:X509Certificate");
    if (CkXml_getLastMethodSuccess(xmlSigned) == FALSE) {
        printf("Failed to get X509Certificate from the signed XML.\n");
        CkDateTime_Dispose(dt);
        CkBinData_Dispose(bdTlv);
        CkXml_Dispose(xmlSigned);
        CkStringBuilder_Dispose(sbDigestValue);
        CkStringBuilder_Dispose(sbSignatureValue);
        return;
    }

    cert = CkCert_Create();
    success = CkCert_SetFromEncoded(cert,x509Certificate);
    if (success == FALSE) {
        printf("Failed to load signing certificate from base64.\n");
        CkDateTime_Dispose(dt);
        CkBinData_Dispose(bdTlv);
        CkXml_Dispose(xmlSigned);
        CkStringBuilder_Dispose(sbDigestValue);
        CkStringBuilder_Dispose(sbSignatureValue);
        CkCert_Dispose(cert);
        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
    bdPubKey = CkBinData_Create();
    success = CkCert_GetPubKeyDer(cert,TRUE,bdPubKey);
    if (success == FALSE) {
        printf("Failed to get certificate's public key.\n");
        CkDateTime_Dispose(dt);
        CkBinData_Dispose(bdTlv);
        CkXml_Dispose(xmlSigned);
        CkStringBuilder_Dispose(sbDigestValue);
        CkStringBuilder_Dispose(sbSignatureValue);
        CkCert_Dispose(cert);
        CkBinData_Dispose(bdPubKey);
        return;
    }

    // We want to add the binary bytes of the public key (not the base64 string) to the QR code.
    tag = 8;
    CkBinData_AppendByte(bdTlv,tag);
    CkBinData_AppendByte(bdTlv,CkBinData_getNumBytes(bdPubKey));
    CkBinData_AppendBd(bdTlv,bdPubKey);

    // Show the public key in base64 format:
    printf("Certificate public key:\n");
    printf("%s\n",CkBinData_getEncoded(bdPubKey,"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
    bdCertSig = CkBinData_Create();
    success = CkCert_GetSignature(cert,bdCertSig);
    if (success == FALSE) {
        printf("Failed to get certificate's signature.\n");
        CkDateTime_Dispose(dt);
        CkBinData_Dispose(bdTlv);
        CkXml_Dispose(xmlSigned);
        CkStringBuilder_Dispose(sbDigestValue);
        CkStringBuilder_Dispose(sbSignatureValue);
        CkCert_Dispose(cert);
        CkBinData_Dispose(bdPubKey);
        CkBinData_Dispose(bdCertSig);
        return;
    }

    // We want to add the binary bytes of the signature (not the base64 string) to the QR code.
    tag = 9;
    CkBinData_AppendByte(bdTlv,tag);
    CkBinData_AppendByte(bdTlv,CkBinData_getNumBytes(bdCertSig));
    CkBinData_AppendBd(bdTlv,bdCertSig);

    // Show the cert's signature in hex format:
    printf("Certificate signature:\n");
    printf("%s\n",CkBinData_getEncoded(bdCertSig,"hex"));

    // ----------------------------------------------------------------------------------------------------------------------------------------------
    // At this point the full QR code is contained in bdTlv.
    // Get it as a base64 string
    qr_base64 = CkBinData_getEncoded(bdTlv,"base64");
    printf("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>

    xmlQR = CkXml_Create();
    CkXml_putTag(xmlQR,"cac:AdditionalDocumentReference");
    CkXml_UpdateChildContent(xmlQR,"cbc:ID","QR");
    CkXml_UpdateAttrAt(xmlQR,"cac:Attachment|cbc:EmbeddedDocumentBinaryObject",TRUE,"mimeCode","text/plain");
    CkXml_UpdateChildContent(xmlQR,"cac:Attachment|cbc:EmbeddedDocumentBinaryObject",CkBinData_getEncoded(bdTlv,"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>

    sbSignedXml = CkStringBuilder_Create();
    success = CkStringBuilder_LoadFile(sbSignedXml,signedXmlFilePath,"utf-8");
    if (success == FALSE) {
        printf("Failed to load previously signed XML file.\n");
        CkDateTime_Dispose(dt);
        CkBinData_Dispose(bdTlv);
        CkXml_Dispose(xmlSigned);
        CkStringBuilder_Dispose(sbDigestValue);
        CkStringBuilder_Dispose(sbSignatureValue);
        CkCert_Dispose(cert);
        CkBinData_Dispose(bdPubKey);
        CkBinData_Dispose(bdCertSig);
        CkXml_Dispose(xmlQR);
        CkStringBuilder_Dispose(sbSignedXml);
        return;
    }

    sbReplaceStr = CkStringBuilder_Create();
    CkXml_putEmitXmlDecl(xmlQR,FALSE);
    CkXml_putEmitCompact(xmlQR,TRUE);
    CkStringBuilder_Append(sbReplaceStr,CkXml_getXml(xmlQR));
    CkStringBuilder_Append(sbReplaceStr,"<cac:Signature>");
    success = CkStringBuilder_ReplaceFirst(sbSignedXml,"<cac:Signature>",CkStringBuilder_getAsString(sbReplaceStr));
    if (success == FALSE) {
        printf("Did not find <cac:Signature> in the signed XML\n");
        CkDateTime_Dispose(dt);
        CkBinData_Dispose(bdTlv);
        CkXml_Dispose(xmlSigned);
        CkStringBuilder_Dispose(sbDigestValue);
        CkStringBuilder_Dispose(sbSignatureValue);
        CkCert_Dispose(cert);
        CkBinData_Dispose(bdPubKey);
        CkBinData_Dispose(bdCertSig);
        CkXml_Dispose(xmlQR);
        CkStringBuilder_Dispose(sbSignedXml);
        CkStringBuilder_Dispose(sbReplaceStr);
        return;
    }

    // Save the updated signed XML.
    success = CkStringBuilder_WriteFile(sbSignedXml,"qa_output/signedXML_withQR.xml","utf-8",FALSE);

    // ----------------------------------------
    // Verify the updated signed XML to make sure we didn't invalidate the signature...
    verifier = CkXmlDSig_Create();
    success = CkXmlDSig_LoadSignatureSb(verifier,sbSignedXml);
    if (success != TRUE) {
        printf("%s\n",CkXmlDSig_lastErrorText(verifier));
        CkDateTime_Dispose(dt);
        CkBinData_Dispose(bdTlv);
        CkXml_Dispose(xmlSigned);
        CkStringBuilder_Dispose(sbDigestValue);
        CkStringBuilder_Dispose(sbSignatureValue);
        CkCert_Dispose(cert);
        CkBinData_Dispose(bdPubKey);
        CkBinData_Dispose(bdCertSig);
        CkXml_Dispose(xmlQR);
        CkStringBuilder_Dispose(sbSignedXml);
        CkStringBuilder_Dispose(sbReplaceStr);
        CkXmlDSig_Dispose(verifier);
        return;
    }

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

    numSigs = CkXmlDSig_getNumSignatures(verifier);
    verifyIdx = 0;
    while (verifyIdx < numSigs) {
        CkXmlDSig_putSelector(verifier,verifyIdx);
        verified = CkXmlDSig_VerifySignature(verifier,TRUE);
        if (verified != TRUE) {
            printf("%s\n",CkXmlDSig_lastErrorText(verifier));
            CkDateTime_Dispose(dt);
            CkBinData_Dispose(bdTlv);
            CkXml_Dispose(xmlSigned);
            CkStringBuilder_Dispose(sbDigestValue);
            CkStringBuilder_Dispose(sbSignatureValue);
            CkCert_Dispose(cert);
            CkBinData_Dispose(bdPubKey);
            CkBinData_Dispose(bdCertSig);
            CkXml_Dispose(xmlQR);
            CkStringBuilder_Dispose(sbSignedXml);
            CkStringBuilder_Dispose(sbReplaceStr);
            CkXmlDSig_Dispose(verifier);
            return;
        }

        verifyIdx = verifyIdx + 1;
    }

    printf("All signatures were successfully verified.\n");


    CkDateTime_Dispose(dt);
    CkBinData_Dispose(bdTlv);
    CkXml_Dispose(xmlSigned);
    CkStringBuilder_Dispose(sbDigestValue);
    CkStringBuilder_Dispose(sbSignatureValue);
    CkCert_Dispose(cert);
    CkBinData_Dispose(bdPubKey);
    CkBinData_Dispose(bdCertSig);
    CkXml_Dispose(xmlQR);
    CkStringBuilder_Dispose(sbSignedXml);
    CkStringBuilder_Dispose(sbReplaceStr);
    CkXmlDSig_Dispose(verifier);

    }

 

© 2000-2024 Chilkat Software, Inc. All Rights Reserved.