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

DataFlex 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
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

 

 

 

(DataFlex) 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 ActiveX Downloads

ActiveX for 32-bit and 64-bit Windows

Use ChilkatAx-win32.pkg

Procedure Test
    Boolean iSuccess
    String sSellerName
    String sVatNumber
    Handle hoDt
    String sTimeStamp
    String sInvoiceTotal
    String sVatTotal
    Handle hoBdTlv
    String sCharset
    Integer iTag
    String sSignedXmlFilePath
    Handle hoXmlSigned
    Variant vSbDigestValue
    Handle hoSbDigestValue
    Variant vSbSignatureValue
    Handle hoSbSignatureValue
    String sX509Certificate
    Handle hoCert
    Variant vBdPubKey
    Handle hoBdPubKey
    Variant vBdCertSig
    Handle hoBdCertSig
    String sQr_base64
    Handle hoXmlQR
    Variant vSbSignedXml
    Handle hoSbSignedXml
    Handle hoSbReplaceStr
    Handle hoVerifier
    Integer iNumSigs
    Integer iVerifyIdx
    Boolean iVerified
    String sTemp1
    Integer iTemp1
    Boolean bTemp1

    // 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:
    Move "Firoz Ashraf" To sSellerName
    Move "1234567891" To sVatNumber

    // 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'
    Get Create (RefClass(cComCkDateTime)) To hoDt
    If (Not(IsComObjectCreated(hoDt))) Begin
        Send CreateComObject of hoDt
    End
    Get ComSetFromCurrentSystemTime Of hoDt To iSuccess
    Get ComGetAsTimestamp Of hoDt False To sTimeStamp
    Move "100.00" To sInvoiceTotal
    Move "15.00" To sVatTotal

    // TLV encode into a Chilkat BinData object.
    Get Create (RefClass(cComChilkatBinData)) To hoBdTlv
    If (Not(IsComObjectCreated(hoBdTlv))) Begin
        Send CreateComObject of hoBdTlv
    End

    Move "utf-8" To sCharset

    Move 1 To iTag
    Get ComAppendByte Of hoBdTlv iTag To iSuccess
    Get ComAppendCountedString Of hoBdTlv 1 False sSellerName sCharset To iSuccess
    Move (iTag + 1) To iTag
    // This is tag 2
    Get ComAppendByte Of hoBdTlv iTag To iSuccess
    Get ComAppendCountedString Of hoBdTlv 1 False sVatNumber sCharset To iSuccess
    Move (iTag + 1) To iTag
    // This is tag 3
    Get ComAppendByte Of hoBdTlv iTag To iSuccess
    Get ComAppendCountedString Of hoBdTlv 1 False sTimeStamp sCharset To iSuccess
    Move (iTag + 1) To iTag
    // This is tag 4
    Get ComAppendByte Of hoBdTlv iTag To iSuccess
    Get ComAppendCountedString Of hoBdTlv 1 False sInvoiceTotal sCharset To iSuccess
    Move (iTag + 1) To iTag
    // This is tag 5
    Get ComAppendByte Of hoBdTlv iTag To iSuccess
    Get ComAppendCountedString Of hoBdTlv 1 False sVatTotal sCharset To iSuccess

    // ----------------------------------------------------------------------------------------------------------------------------------------------
    // 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...
    Move "qa_data/zatca/testing/SignedXML.xml" To sSignedXmlFilePath
    Get Create (RefClass(cComChilkatXml)) To hoXmlSigned
    If (Not(IsComObjectCreated(hoXmlSigned))) Begin
        Send CreateComObject of hoXmlSigned
    End
    Get ComLoadXmlFile Of hoXmlSigned sSignedXmlFilePath To iSuccess
    If (iSuccess = False) Begin
        Get ComLastErrorText Of hoXmlSigned To sTemp1
        Showln sTemp1
        Procedure_Return
    End

    // digestValue is a base64 string.
    Get Create (RefClass(cComChilkatStringBuilder)) To hoSbDigestValue
    If (Not(IsComObjectCreated(hoSbDigestValue))) Begin
        Send CreateComObject of hoSbDigestValue
    End
    Get pvComObject of hoSbDigestValue to vSbDigestValue
    Get ComGetChildContentSb Of hoXmlSigned "ext:UBLExtensions|ext:UBLExtension|ext:ExtensionContent|sig:UBLDocumentSignatures|sac:SignatureInformation|ds:Signature|ds:SignedInfo|ds:Reference[0]|ds:DigestValue" vSbDigestValue To iSuccess
    If (iSuccess = False) Begin
        Showln "Failed to get DigestValue from signed XML."
        Procedure_Return
    End

    Get ComGetAsString Of hoSbDigestValue To sTemp1
    Showln "DigestValue = " sTemp1

    // Append the DigestValue base64 string to the TLV.
    Move 6 To iTag
    Get ComAppendByte Of hoBdTlv iTag To iSuccess
    Get ComLength Of hoSbDigestValue To iTemp1
    Get ComAppendByte Of hoBdTlv iTemp1 To iSuccess
    Get pvComObject of hoSbDigestValue to vSbDigestValue
    Get ComAppendSb Of hoBdTlv vSbDigestValue "utf-8" To iSuccess

    // ----------------------------------------------------------------------------------------------------------------------------------------------
    // 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.
    Get Create (RefClass(cComChilkatStringBuilder)) To hoSbSignatureValue
    If (Not(IsComObjectCreated(hoSbSignatureValue))) Begin
        Send CreateComObject of hoSbSignatureValue
    End
    Get pvComObject of hoSbSignatureValue to vSbSignatureValue
    Get ComGetChildContentSb Of hoXmlSigned "ext:UBLExtensions|ext:UBLExtension|ext:ExtensionContent|sig:UBLDocumentSignatures|sac:SignatureInformation|ds:Signature|ds:SignatureValue" vSbSignatureValue To iSuccess
    If (iSuccess = False) Begin
        Showln "Failed to get SignatureValue from signed XML."
        Procedure_Return
    End

    Get ComGetAsString Of hoSbSignatureValue To sTemp1
    Showln "SignatureValue = " sTemp1

    // Append the SignatureValue base64 string to the TLV.
    Move 7 To iTag
    Get ComAppendByte Of hoBdTlv iTag To iSuccess
    Get ComLength Of hoSbSignatureValue To iTemp1
    Get ComAppendByte Of hoBdTlv iTemp1 To iSuccess
    Get pvComObject of hoSbSignatureValue to vSbSignatureValue
    Get ComAppendSb Of hoBdTlv vSbSignatureValue "utf-8" To iSuccess

    // ----------------------------------------------------------------------------------------------------------------------------------------------
    // Tag 8 will contain the public key of the signing certificate.
    // The signing certificate is available within the signed XML at <ds:X509Certificate>.
    Get ComGetChildContent Of hoXmlSigned "ext:UBLExtensions|ext:UBLExtension|ext:ExtensionContent|sig:UBLDocumentSignatures|sac:SignatureInformation|ds:Signature|ds:KeyInfo|ds:X509Data|ds:X509Certificate" To sX509Certificate
    Get ComLastMethodSuccess Of hoXmlSigned To bTemp1
    If (bTemp1 = False) Begin
        Showln "Failed to get X509Certificate from the signed XML."
        Procedure_Return
    End

    Get Create (RefClass(cComChilkatCert)) To hoCert
    If (Not(IsComObjectCreated(hoCert))) Begin
        Send CreateComObject of hoCert
    End
    Get ComSetFromEncoded Of hoCert sX509Certificate To iSuccess
    If (iSuccess = False) Begin
        Showln "Failed to load signing certificate from base64."
        Procedure_Return
    End

    // 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
    Get Create (RefClass(cComChilkatBinData)) To hoBdPubKey
    If (Not(IsComObjectCreated(hoBdPubKey))) Begin
        Send CreateComObject of hoBdPubKey
    End
    Get pvComObject of hoBdPubKey to vBdPubKey
    Get ComGetPubKeyDer Of hoCert True vBdPubKey To iSuccess
    If (iSuccess = False) Begin
        Showln "Failed to get certificate's public key."
        Procedure_Return
    End

    // We want to add the binary bytes of the public key (not the base64 string) to the QR code.
    Move 8 To iTag
    Get ComAppendByte Of hoBdTlv iTag To iSuccess
    Get ComNumBytes Of hoBdPubKey To iTemp1
    Get ComAppendByte Of hoBdTlv iTemp1 To iSuccess
    Get pvComObject of hoBdPubKey to vBdPubKey
    Get ComAppendBd Of hoBdTlv vBdPubKey To iSuccess

    // Show the public key in base64 format:
    Showln "Certificate public key:"
    Get ComGetEncoded Of hoBdPubKey "base64" To sTemp1
    Showln sTemp1

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

    // Note: The cert.GetPubKeyDer method was added in Chilkat v9.5.0.92
    Get Create (RefClass(cComChilkatBinData)) To hoBdCertSig
    If (Not(IsComObjectCreated(hoBdCertSig))) Begin
        Send CreateComObject of hoBdCertSig
    End
    Get pvComObject of hoBdCertSig to vBdCertSig
    Get ComGetSignature Of hoCert vBdCertSig To iSuccess
    If (iSuccess = False) Begin
        Showln "Failed to get certificate's signature."
        Procedure_Return
    End

    // We want to add the binary bytes of the signature (not the base64 string) to the QR code.
    Move 9 To iTag
    Get ComAppendByte Of hoBdTlv iTag To iSuccess
    Get ComNumBytes Of hoBdCertSig To iTemp1
    Get ComAppendByte Of hoBdTlv iTemp1 To iSuccess
    Get pvComObject of hoBdCertSig to vBdCertSig
    Get ComAppendBd Of hoBdTlv vBdCertSig To iSuccess

    // Show the cert's signature in hex format:
    Showln "Certificate signature:"
    Get ComGetEncoded Of hoBdCertSig "hex" To sTemp1
    Showln sTemp1

    // ----------------------------------------------------------------------------------------------------------------------------------------------
    // At this point the full QR code is contained in bdTlv.
    // Get it as a base64 string
    Get ComGetEncoded Of hoBdTlv "base64" To sQr_base64
    Showln "QR: " sQr_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>

    Get Create (RefClass(cComChilkatXml)) To hoXmlQR
    If (Not(IsComObjectCreated(hoXmlQR))) Begin
        Send CreateComObject of hoXmlQR
    End
    Set ComTag Of hoXmlQR To "cac:AdditionalDocumentReference"
    Send ComUpdateChildContent To hoXmlQR "cbc:ID" "QR"
    Get ComUpdateAttrAt Of hoXmlQR "cac:Attachment|cbc:EmbeddedDocumentBinaryObject" True "mimeCode" "text/plain" To iSuccess
    Get ComGetEncoded Of hoBdTlv "base64" To sTemp1
    Send ComUpdateChildContent To hoXmlQR "cac:Attachment|cbc:EmbeddedDocumentBinaryObject" sTemp1

    // 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>

    Get Create (RefClass(cComChilkatStringBuilder)) To hoSbSignedXml
    If (Not(IsComObjectCreated(hoSbSignedXml))) Begin
        Send CreateComObject of hoSbSignedXml
    End
    Get ComLoadFile Of hoSbSignedXml sSignedXmlFilePath "utf-8" To iSuccess
    If (iSuccess = False) Begin
        Showln "Failed to load previously signed XML file."
        Procedure_Return
    End

    Get Create (RefClass(cComChilkatStringBuilder)) To hoSbReplaceStr
    If (Not(IsComObjectCreated(hoSbReplaceStr))) Begin
        Send CreateComObject of hoSbReplaceStr
    End
    Set ComEmitXmlDecl Of hoXmlQR To False
    Set ComEmitCompact Of hoXmlQR To True
    Get ComGetXml Of hoXmlQR To sTemp1
    Get ComAppend Of hoSbReplaceStr sTemp1 To iSuccess
    Get ComAppend Of hoSbReplaceStr "<cac:Signature>" To iSuccess
    Get ComGetAsString Of hoSbReplaceStr To sTemp1
    Get ComReplaceFirst Of hoSbSignedXml "<cac:Signature>" sTemp1 To iSuccess
    If (iSuccess = False) Begin
        Showln "Did not find <cac:Signature> in the signed XML"
        Procedure_Return
    End

    // Save the updated signed XML.
    Get ComWriteFile Of hoSbSignedXml "qa_output/signedXML_withQR.xml" "utf-8" False To iSuccess

    // ----------------------------------------
    // Verify the updated signed XML to make sure we didn't invalidate the signature...
    Get Create (RefClass(cComChilkatXmlDSig)) To hoVerifier
    If (Not(IsComObjectCreated(hoVerifier))) Begin
        Send CreateComObject of hoVerifier
    End
    Get pvComObject of hoSbSignedXml to vSbSignedXml
    Get ComLoadSignatureSb Of hoVerifier vSbSignedXml To iSuccess
    If (iSuccess <> True) Begin
        Get ComLastErrorText Of hoVerifier To sTemp1
        Showln sTemp1
        Procedure_Return
    End

    // ---------------- This is important -----------------------------------------
    // Starting in Chilkat v9.5.0.92, specify "ZATCA" in uncommon options 
    // to validate signed XML according to ZATCA needs.
    // ----------------------------------------------------------------------------
    Set ComUncommonOptions Of hoVerifier To "ZATCA"

    Get ComNumSignatures Of hoVerifier To iNumSigs
    Move 0 To iVerifyIdx
    While (iVerifyIdx < iNumSigs)
        Set ComSelector Of hoVerifier To iVerifyIdx
        Get ComVerifySignature Of hoVerifier True To iVerified
        If (iVerified <> True) Begin
            Get ComLastErrorText Of hoVerifier To sTemp1
            Showln sTemp1
            Procedure_Return
        End

        Move (iVerifyIdx + 1) To iVerifyIdx
    Loop

    Showln "All signatures were successfully verified."


End_Procedure

 

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