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

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

 

 

 

(Objective-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 Objective-C Library Downloads

MAC OS X (Cocoa) Libs

iOS Libs

#import <NSString.h>
#import <CkoDateTime.h>
#import <CkoBinData.h>
#import <CkoXml.h>
#import <CkoStringBuilder.h>
#import <CkoCert.h>
#import <CkoXmlDSig.h>

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

BOOL success;

// 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:
NSString *sellerName = @"Firoz Ashraf";
NSString *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'
CkoDateTime *dt = [[CkoDateTime alloc] init];
[dt SetFromCurrentSystemTime];
NSString *timeStamp = [dt GetAsTimestamp: NO];
NSString *invoiceTotal = @"100.00";
NSString *vatTotal = @"15.00";

// TLV encode into a Chilkat BinData object.
CkoBinData *bdTlv = [[CkoBinData alloc] init];

NSString *charset = @"utf-8";

int tag = 1;
[bdTlv AppendByte: [NSNumber numberWithInt: tag]];
[bdTlv AppendCountedString: [NSNumber numberWithInt: 1] bigEndian: NO str: sellerName charset: charset];
tag = tag + 1;
// This is tag 2
[bdTlv AppendByte: [NSNumber numberWithInt: tag]];
[bdTlv AppendCountedString: [NSNumber numberWithInt: 1] bigEndian: NO str: vatNumber charset: charset];
tag = tag + 1;
// This is tag 3
[bdTlv AppendByte: [NSNumber numberWithInt: tag]];
[bdTlv AppendCountedString: [NSNumber numberWithInt: 1] bigEndian: NO str: timeStamp charset: charset];
tag = tag + 1;
// This is tag 4
[bdTlv AppendByte: [NSNumber numberWithInt: tag]];
[bdTlv AppendCountedString: [NSNumber numberWithInt: 1] bigEndian: NO str: invoiceTotal charset: charset];
tag = tag + 1;
// This is tag 5
[bdTlv AppendByte: [NSNumber numberWithInt: tag]];
[bdTlv AppendCountedString: [NSNumber numberWithInt: 1] bigEndian: NO str: vatTotal charset: 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...
NSString *signedXmlFilePath = @"qa_data/zatca/testing/SignedXML.xml";
CkoXml *xmlSigned = [[CkoXml alloc] init];
success = [xmlSigned LoadXmlFile: signedXmlFilePath];
if (success == NO) {
    NSLog(@"%@",xmlSigned.LastErrorText);
    return;
}

// digestValue is a base64 string.
CkoStringBuilder *sbDigestValue = [[CkoStringBuilder alloc] init];
success = [xmlSigned GetChildContentSb: @"ext:UBLExtensions|ext:UBLExtension|ext:ExtensionContent|sig:UBLDocumentSignatures|sac:SignatureInformation|ds:Signature|ds:SignedInfo|ds:Reference[0]|ds:DigestValue" sb: sbDigestValue];
if (success == NO) {
    NSLog(@"%@",@"Failed to get DigestValue from signed XML.");
    return;
}

NSLog(@"%@%@",@"DigestValue = ",[sbDigestValue GetAsString]);

// Append the DigestValue base64 string to the TLV.
tag = 6;
[bdTlv AppendByte: [NSNumber numberWithInt: tag]];
[bdTlv AppendByte: sbDigestValue.Length];
[bdTlv AppendSb: sbDigestValue charset: @"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.
CkoStringBuilder *sbSignatureValue = [[CkoStringBuilder alloc] init];
success = [xmlSigned GetChildContentSb: @"ext:UBLExtensions|ext:UBLExtension|ext:ExtensionContent|sig:UBLDocumentSignatures|sac:SignatureInformation|ds:Signature|ds:SignatureValue" sb: sbSignatureValue];
if (success == NO) {
    NSLog(@"%@",@"Failed to get SignatureValue from signed XML.");
    return;
}

NSLog(@"%@%@",@"SignatureValue = ",[sbSignatureValue GetAsString]);

// Append the SignatureValue base64 string to the TLV.
tag = 7;
[bdTlv AppendByte: [NSNumber numberWithInt: tag]];
[bdTlv AppendByte: sbSignatureValue.Length];
[bdTlv AppendSb: sbSignatureValue charset: @"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>.
NSString *x509Certificate = [xmlSigned GetChildContent: @"ext:UBLExtensions|ext:UBLExtension|ext:ExtensionContent|sig:UBLDocumentSignatures|sac:SignatureInformation|ds:Signature|ds:KeyInfo|ds:X509Data|ds:X509Certificate"];
if (xmlSigned.LastMethodSuccess == NO) {
    NSLog(@"%@",@"Failed to get X509Certificate from the signed XML.");
    return;
}

CkoCert *cert = [[CkoCert alloc] init];
success = [cert SetFromEncoded: x509Certificate];
if (success == NO) {
    NSLog(@"%@",@"Failed to load signing certificate from base64.");
    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
CkoBinData *bdPubKey = [[CkoBinData alloc] init];
success = [cert GetPubKeyDer: YES bd: bdPubKey];
if (success == NO) {
    NSLog(@"%@",@"Failed to get certificate's public key.");
    return;
}

// We want to add the binary bytes of the public key (not the base64 string) to the QR code.
tag = 8;
[bdTlv AppendByte: [NSNumber numberWithInt: tag]];
[bdTlv AppendByte: bdPubKey.NumBytes];
[bdTlv AppendBd: bdPubKey];

// Show the public key in base64 format:
NSLog(@"%@",@"Certificate public key:");
NSLog(@"%@",[bdPubKey GetEncoded: @"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
CkoBinData *bdCertSig = [[CkoBinData alloc] init];
success = [cert GetSignature: bdCertSig];
if (success == NO) {
    NSLog(@"%@",@"Failed to get certificate's signature.");
    return;
}

// We want to add the binary bytes of the signature (not the base64 string) to the QR code.
tag = 9;
[bdTlv AppendByte: [NSNumber numberWithInt: tag]];
[bdTlv AppendByte: bdCertSig.NumBytes];
[bdTlv AppendBd: bdCertSig];

// Show the cert's signature in hex format:
NSLog(@"%@",@"Certificate signature:");
NSLog(@"%@",[bdCertSig GetEncoded: @"hex"]);

// ----------------------------------------------------------------------------------------------------------------------------------------------
// At this point the full QR code is contained in bdTlv.
// Get it as a base64 string
NSString *qr_base64 = [bdTlv GetEncoded: @"base64"];
NSLog(@"%@%@",@"QR: ",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>

CkoXml *xmlQR = [[CkoXml alloc] init];
xmlQR.Tag = @"cac:AdditionalDocumentReference";
[xmlQR UpdateChildContent: @"cbc:ID" value: @"QR"];
[xmlQR UpdateAttrAt: @"cac:Attachment|cbc:EmbeddedDocumentBinaryObject" autoCreate: YES attrName: @"mimeCode" attrValue: @"text/plain"];
[xmlQR UpdateChildContent: @"cac:Attachment|cbc:EmbeddedDocumentBinaryObject" value: [bdTlv GetEncoded: @"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>

CkoStringBuilder *sbSignedXml = [[CkoStringBuilder alloc] init];
success = [sbSignedXml LoadFile: signedXmlFilePath charset: @"utf-8"];
if (success == NO) {
    NSLog(@"%@",@"Failed to load previously signed XML file.");
    return;
}

CkoStringBuilder *sbReplaceStr = [[CkoStringBuilder alloc] init];
xmlQR.EmitXmlDecl = NO;
xmlQR.EmitCompact = YES;
[sbReplaceStr Append: [xmlQR GetXml]];
[sbReplaceStr Append: @"<cac:Signature>"];
success = [sbSignedXml ReplaceFirst: @"<cac:Signature>" replacement: [sbReplaceStr GetAsString]];
if (success == NO) {
    NSLog(@"%@",@"Did not find <cac:Signature> in the signed XML");
    return;
}

// Save the updated signed XML.
success = [sbSignedXml WriteFile: @"qa_output/signedXML_withQR.xml" charset: @"utf-8" emitBom: NO];

// ----------------------------------------
// Verify the updated signed XML to make sure we didn't invalidate the signature...
CkoXmlDSig *verifier = [[CkoXmlDSig alloc] init];
success = [verifier LoadSignatureSb: sbSignedXml];
if (success != YES) {
    NSLog(@"%@",verifier.LastErrorText);
    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.UncommonOptions = @"ZATCA";

int numSigs = [verifier.NumSignatures intValue];
int verifyIdx = 0;
while (verifyIdx < numSigs) {
    verifier.Selector = [NSNumber numberWithInt: verifyIdx];
    BOOL verified = [verifier VerifySignature: YES];
    if (verified != YES) {
        NSLog(@"%@",verifier.LastErrorText);
        return;
    }

    verifyIdx = verifyIdx + 1;
}

NSLog(@"%@",@"All signatures were successfully verified.");
 

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