← Back to Blog

ECDSA Cryptographic Signing for ZATCA UBL 2.1 XML Invoices in Node.js


BLUF: Achieving compliance with Saudi Arabia's ZATCA Phase 2 (Fatoora) e-invoicing mandate requires generating tamper-proof cryptographic signatures for all UBL 2.1 XML tax invoices. The pipeline demands canonicalizing XML (C14N11), hashing the normalized document with SHA-256, and signing it with an ECDSA private key on the secp256k1 elliptic curve tied to an onboarded Cryptographic Stamp Identifier (CSID). This guide provides the complete production architecture and an illustrative Node.js reference architecture outlining the conceptual cryptographic pipeline.

ZATCA Phase 2 Architectural Mandates & Cryptographic Specifications

The Zakat, Tax and Customs Authority (ZATCA) introduced Phase 2 of the Fatoora e-invoicing mandate to integrate enterprise ERPs and billing platforms directly with governmental clearing endpoints. For Standard B2B tax invoices, real-time clearance is mandatory before sending the invoice to the customer. For Simplified B2C invoices, the invoice must be issued immediately with an encrypted QR code and reported to ZATCA within 24 hours.

The technical specification enforces strict cryptographic validation:

  • Invoice Hash: A Base64-encoded SHA-256 digest computed across the canonicalized XML representation of the invoice, excluding signature elements.
  • Digital Signature: An ECDSA signature over the secp256k1 elliptic curve, encoded in DER/ASN.1 and Base64 formatted.
  • Certificate Identification: Embedding the onboarding X.509 Cryptographic Stamp Identifier (CSID) and hashing it inside the signing certificate properties.

The 5-Stage Invoice Transformation Pipeline in Node.js

  1. Element Exclusion: Strip mutable and signing-specific nodes per ZATCA specification (ext:UBLExtensions, cac:Signature, and cac:AdditionalDocumentReference where cbc:ID is 'QR') prior to digest generation. Core schema version elements like cbc:UBLVersionID remain untouched.
  2. C14N Canonicalization: Normalize XML whitespace, attribute ordering, and namespace declarations to produce a deterministic string representation.
  3. SHA-256 Hashing: Compute the cryptographic digest across the UTF-8 bytes of the canonicalized XML.
  4. ECDSA Signing: Sign the SHA-256 digest using the secp256k1 private key extracted during CSID onboarding.
  5. Hash Chaining & TLV QR Generation: Prepend the Previous Invoice Hash (PIH) to maintain immutable hash sequence, and format the mandatory 9 TLV fields for the printed QR code.

Illustrative TypeScript Implementation (Not Validated Against ZATCA Sandbox)

Engineering Disclaimer: The following code is an illustrative architectural reference only. It has not been validated against the official ZATCA Sandbox or verified against ZATCA's official Java SDK. Teams must test and validate their exact signature routine against the official ZATCA compliance validator before production use.

import crypto from "node:crypto";

/**
 * Signs a canonicalized ZATCA UBL 2.1 XML invoice using an ECDSA secp256k1 private key.
 * ILLUSTRATIVE ONLY - NOT VALIDATED AGAINST OFFICIAL ZATCA SANDBOX.
 * In production, test against the official ZATCA Java SDK / Sandbox validator
 * to confirm whether your integration requires direct signing or pre-hashed digest signing.
 */
export function signZatcaInvoice(
  canonicalXml: string | Buffer,
  privateKeyPem: string
): { invoiceHashBase64: string; signatureBase64: string } {
  const xmlBuffer = Buffer.isBuffer(canonicalXml) ? canonicalXml : Buffer.from(canonicalXml, "utf-8");
  const invoiceHash = crypto.createHash("sha256").update(xmlBuffer).digest();
  const signer = crypto.createSign("SHA256");
  signer.update(xmlBuffer);
  const signatureBase64 = signer.sign(privateKeyPem, "base64");
  return { invoiceHashBase64: invoiceHash.toString("base64"), signatureBase64 };
}

/** Sign pre-computed 32-byte SHA-256 digest directly without double hashing */
export function signPrecomputedDigest(digestBuffer: Buffer, privateKeyPem: string): string {
  return crypto.sign(null, digestBuffer, { key: privateKeyPem, dsaEncoding: "der" }).toString("base64");
}

/**
 * Validates whether a signature matches the given invoice hash and public key.
 */
export function verifyZatcaSignature(
  invoiceHashBase64: string,
  signatureBase64: string,
  publicKeyPem: string
): boolean {
  const hashBuffer = Buffer.from(invoiceHashBase64, "base64");
  const verify = crypto.createVerify("SHA256");
  verify.update(hashBuffer);
  return verify.verify(publicKeyPem, signatureBase64, "base64");
}

Operational Verification and Example SLOs to Monitor

The following Prometheus and Grafana alerts represent example internal operational SLOs for your engineering team, rather than statutory thresholds mandated by ZATCA:

  • zatca_api_clearance_latency_p99 < 0.8s (Example SLO): Internal latency target to prevent checkout blocking on synchronous B2B clearance.
  • zatca_reporting_dlq_count == 0: Verify that background reporting workers never encounter unhandled fatal schema rejections.
  • zatca_c14n_hash_mismatch == 0: Zero tolerance for canonicalization drift or character encoding anomalies.

Summary Recommendations

Store your CSID cryptographic keys inside a Hardware Security Module (HSM) or cloud KMS (AWS KMS / Google Cloud KMS) with role-based audit logs. Test all XML schema transformations against ZATCA's sandbox environment before initiating Phase 2 production clearance.

Commercial Engineering & Platform Infrastructure Advisory

Need hands-on senior engineering to audit, scale, or stabilize your infrastructure?

From bare-metal Kubernetes and immutable Talos Linux to drastically cutting cloud infrastructure bills, resolving PostgreSQL deadlocks, and architecting sovereign AI systems, I work directly with production engineering teams to deliver resilient foundations.