SQL Server
SQL Server
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 SQL Server Downloads
-- Important: See this note about string length limitations for strings returned by sp_OAMethod calls.
--
CREATE PROCEDURE ChilkatSample
AS
BEGIN
DECLARE @hr int
DECLARE @iTmp0 int
-- Important: Do not use nvarchar(max). See the warning about using nvarchar(max).
DECLARE @sTmp0 nvarchar(4000)
DECLARE @success int
SELECT @success = 0
-- 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:
DECLARE @sellerName nvarchar(4000)
SELECT @sellerName = 'Firoz Ashraf'
DECLARE @vatNumber nvarchar(4000)
SELECT @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'
DECLARE @dt int
EXEC @hr = sp_OACreate 'Chilkat.CkDateTime', @dt OUT
IF @hr <> 0
BEGIN
PRINT 'Failed to create ActiveX component'
RETURN
END
EXEC sp_OAMethod @dt, 'SetFromCurrentSystemTime', @success OUT
DECLARE @timeStamp nvarchar(4000)
EXEC sp_OAMethod @dt, 'GetAsTimestamp', @timeStamp OUT, 0
DECLARE @invoiceTotal nvarchar(4000)
SELECT @invoiceTotal = '100.00'
DECLARE @vatTotal nvarchar(4000)
SELECT @vatTotal = '15.00'
-- TLV encode into a Chilkat BinData object.
DECLARE @bdTlv int
EXEC @hr = sp_OACreate 'Chilkat.BinData', @bdTlv OUT
DECLARE @charset nvarchar(4000)
SELECT @charset = 'utf-8'
DECLARE @tag int
SELECT @tag = 1
EXEC sp_OAMethod @bdTlv, 'AppendByte', @success OUT, @tag
EXEC sp_OAMethod @bdTlv, 'AppendCountedString', @success OUT, 1, 0, @sellerName, @charset
SELECT @tag = @tag + 1
-- This is tag 2
EXEC sp_OAMethod @bdTlv, 'AppendByte', @success OUT, @tag
EXEC sp_OAMethod @bdTlv, 'AppendCountedString', @success OUT, 1, 0, @vatNumber, @charset
SELECT @tag = @tag + 1
-- This is tag 3
EXEC sp_OAMethod @bdTlv, 'AppendByte', @success OUT, @tag
EXEC sp_OAMethod @bdTlv, 'AppendCountedString', @success OUT, 1, 0, @timeStamp, @charset
SELECT @tag = @tag + 1
-- This is tag 4
EXEC sp_OAMethod @bdTlv, 'AppendByte', @success OUT, @tag
EXEC sp_OAMethod @bdTlv, 'AppendCountedString', @success OUT, 1, 0, @invoiceTotal, @charset
SELECT @tag = @tag + 1
-- This is tag 5
EXEC sp_OAMethod @bdTlv, 'AppendByte', @success OUT, @tag
EXEC sp_OAMethod @bdTlv, 'AppendCountedString', @success OUT, 1, 0, @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...
DECLARE @signedXmlFilePath nvarchar(4000)
SELECT @signedXmlFilePath = 'qa_data/zatca/testing/SignedXML.xml'
DECLARE @xmlSigned int
EXEC @hr = sp_OACreate 'Chilkat.Xml', @xmlSigned OUT
EXEC sp_OAMethod @xmlSigned, 'LoadXmlFile', @success OUT, @signedXmlFilePath
IF @success = 0
BEGIN
EXEC sp_OAGetProperty @xmlSigned, 'LastErrorText', @sTmp0 OUT
PRINT @sTmp0
EXEC @hr = sp_OADestroy @dt
EXEC @hr = sp_OADestroy @bdTlv
EXEC @hr = sp_OADestroy @xmlSigned
RETURN
END
-- digestValue is a base64 string.
DECLARE @sbDigestValue int
EXEC @hr = sp_OACreate 'Chilkat.StringBuilder', @sbDigestValue OUT
EXEC sp_OAMethod @xmlSigned, 'GetChildContentSb', @success OUT, 'ext:UBLExtensions|ext:UBLExtension|ext:ExtensionContent|sig:UBLDocumentSignatures|sac:SignatureInformation|ds:Signature|ds:SignedInfo|ds:Reference[0]|ds:DigestValue', @sbDigestValue
IF @success = 0
BEGIN
PRINT 'Failed to get DigestValue from signed XML.'
EXEC @hr = sp_OADestroy @dt
EXEC @hr = sp_OADestroy @bdTlv
EXEC @hr = sp_OADestroy @xmlSigned
EXEC @hr = sp_OADestroy @sbDigestValue
RETURN
END
EXEC sp_OAMethod @sbDigestValue, 'GetAsString', @sTmp0 OUT
PRINT 'DigestValue = ' + @sTmp0
-- Append the DigestValue base64 string to the TLV.
SELECT @tag = 6
EXEC sp_OAMethod @bdTlv, 'AppendByte', @success OUT, @tag
EXEC sp_OAGetProperty @sbDigestValue, 'Length', @iTmp0 OUT
EXEC sp_OAMethod @bdTlv, 'AppendByte', @success OUT, @iTmp0
EXEC sp_OAMethod @bdTlv, 'AppendSb', @success OUT, @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.
DECLARE @sbSignatureValue int
EXEC @hr = sp_OACreate 'Chilkat.StringBuilder', @sbSignatureValue OUT
EXEC sp_OAMethod @xmlSigned, 'GetChildContentSb', @success OUT, 'ext:UBLExtensions|ext:UBLExtension|ext:ExtensionContent|sig:UBLDocumentSignatures|sac:SignatureInformation|ds:Signature|ds:SignatureValue', @sbSignatureValue
IF @success = 0
BEGIN
PRINT 'Failed to get SignatureValue from signed XML.'
EXEC @hr = sp_OADestroy @dt
EXEC @hr = sp_OADestroy @bdTlv
EXEC @hr = sp_OADestroy @xmlSigned
EXEC @hr = sp_OADestroy @sbDigestValue
EXEC @hr = sp_OADestroy @sbSignatureValue
RETURN
END
EXEC sp_OAMethod @sbSignatureValue, 'GetAsString', @sTmp0 OUT
PRINT 'SignatureValue = ' + @sTmp0
-- Append the SignatureValue base64 string to the TLV.
SELECT @tag = 7
EXEC sp_OAMethod @bdTlv, 'AppendByte', @success OUT, @tag
EXEC sp_OAGetProperty @sbSignatureValue, 'Length', @iTmp0 OUT
EXEC sp_OAMethod @bdTlv, 'AppendByte', @success OUT, @iTmp0
EXEC sp_OAMethod @bdTlv, 'AppendSb', @success OUT, @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>.
DECLARE @x509Certificate nvarchar(4000)
EXEC sp_OAMethod @xmlSigned, 'GetChildContent', @x509Certificate OUT, 'ext:UBLExtensions|ext:UBLExtension|ext:ExtensionContent|sig:UBLDocumentSignatures|sac:SignatureInformation|ds:Signature|ds:KeyInfo|ds:X509Data|ds:X509Certificate'
EXEC sp_OAGetProperty @xmlSigned, 'LastMethodSuccess', @iTmp0 OUT
IF @iTmp0 = 0
BEGIN
PRINT 'Failed to get X509Certificate from the signed XML.'
EXEC @hr = sp_OADestroy @dt
EXEC @hr = sp_OADestroy @bdTlv
EXEC @hr = sp_OADestroy @xmlSigned
EXEC @hr = sp_OADestroy @sbDigestValue
EXEC @hr = sp_OADestroy @sbSignatureValue
RETURN
END
DECLARE @cert int
EXEC @hr = sp_OACreate 'Chilkat.Cert', @cert OUT
EXEC sp_OAMethod @cert, 'SetFromEncoded', @success OUT, @x509Certificate
IF @success = 0
BEGIN
PRINT 'Failed to load signing certificate from base64.'
EXEC @hr = sp_OADestroy @dt
EXEC @hr = sp_OADestroy @bdTlv
EXEC @hr = sp_OADestroy @xmlSigned
EXEC @hr = sp_OADestroy @sbDigestValue
EXEC @hr = sp_OADestroy @sbSignatureValue
EXEC @hr = sp_OADestroy @cert
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
DECLARE @bdPubKey int
EXEC @hr = sp_OACreate 'Chilkat.BinData', @bdPubKey OUT
EXEC sp_OAMethod @cert, 'GetPubKeyDer', @success OUT, 1, @bdPubKey
IF @success = 0
BEGIN
PRINT 'Failed to get certificate''s public key.'
EXEC @hr = sp_OADestroy @dt
EXEC @hr = sp_OADestroy @bdTlv
EXEC @hr = sp_OADestroy @xmlSigned
EXEC @hr = sp_OADestroy @sbDigestValue
EXEC @hr = sp_OADestroy @sbSignatureValue
EXEC @hr = sp_OADestroy @cert
EXEC @hr = sp_OADestroy @bdPubKey
RETURN
END
-- We want to add the binary bytes of the public key (not the base64 string) to the QR code.
SELECT @tag = 8
EXEC sp_OAMethod @bdTlv, 'AppendByte', @success OUT, @tag
EXEC sp_OAGetProperty @bdPubKey, 'NumBytes', @iTmp0 OUT
EXEC sp_OAMethod @bdTlv, 'AppendByte', @success OUT, @iTmp0
EXEC sp_OAMethod @bdTlv, 'AppendBd', @success OUT, @bdPubKey
-- Show the public key in base64 format:
PRINT 'Certificate public key:'
EXEC sp_OAMethod @bdPubKey, 'GetEncoded', @sTmp0 OUT, 'base64'
PRINT @sTmp0
-- ----------------------------------------------------------------------------------------------------------------------------------------------
-- Tag 9 will contain the signature contained in the signing certificate.
-- Note: The cert.GetPubKeyDer method was added in Chilkat v9.5.0.92
DECLARE @bdCertSig int
EXEC @hr = sp_OACreate 'Chilkat.BinData', @bdCertSig OUT
EXEC sp_OAMethod @cert, 'GetSignature', @success OUT, @bdCertSig
IF @success = 0
BEGIN
PRINT 'Failed to get certificate''s signature.'
EXEC @hr = sp_OADestroy @dt
EXEC @hr = sp_OADestroy @bdTlv
EXEC @hr = sp_OADestroy @xmlSigned
EXEC @hr = sp_OADestroy @sbDigestValue
EXEC @hr = sp_OADestroy @sbSignatureValue
EXEC @hr = sp_OADestroy @cert
EXEC @hr = sp_OADestroy @bdPubKey
EXEC @hr = sp_OADestroy @bdCertSig
RETURN
END
-- We want to add the binary bytes of the signature (not the base64 string) to the QR code.
SELECT @tag = 9
EXEC sp_OAMethod @bdTlv, 'AppendByte', @success OUT, @tag
EXEC sp_OAGetProperty @bdCertSig, 'NumBytes', @iTmp0 OUT
EXEC sp_OAMethod @bdTlv, 'AppendByte', @success OUT, @iTmp0
EXEC sp_OAMethod @bdTlv, 'AppendBd', @success OUT, @bdCertSig
-- Show the cert's signature in hex format:
PRINT 'Certificate signature:'
EXEC sp_OAMethod @bdCertSig, 'GetEncoded', @sTmp0 OUT, 'hex'
PRINT @sTmp0
-- ----------------------------------------------------------------------------------------------------------------------------------------------
-- At this point the full QR code is contained in bdTlv.
-- Get it as a base64 string
DECLARE @qr_base64 nvarchar(4000)
EXEC sp_OAMethod @bdTlv, 'GetEncoded', @qr_base64 OUT, 'base64'
PRINT '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>
DECLARE @xmlQR int
EXEC @hr = sp_OACreate 'Chilkat.Xml', @xmlQR OUT
EXEC sp_OASetProperty @xmlQR, 'Tag', 'cac:AdditionalDocumentReference'
EXEC sp_OAMethod @xmlQR, 'UpdateChildContent', NULL, 'cbc:ID', 'QR'
EXEC sp_OAMethod @xmlQR, 'UpdateAttrAt', @success OUT, 'cac:Attachment|cbc:EmbeddedDocumentBinaryObject', 1, 'mimeCode', 'text/plain'
EXEC sp_OAMethod @bdTlv, 'GetEncoded', @sTmp0 OUT, 'base64'
EXEC sp_OAMethod @xmlQR, 'UpdateChildContent', NULL, 'cac:Attachment|cbc:EmbeddedDocumentBinaryObject', @sTmp0
-- 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>
DECLARE @sbSignedXml int
EXEC @hr = sp_OACreate 'Chilkat.StringBuilder', @sbSignedXml OUT
EXEC sp_OAMethod @sbSignedXml, 'LoadFile', @success OUT, @signedXmlFilePath, 'utf-8'
IF @success = 0
BEGIN
PRINT 'Failed to load previously signed XML file.'
EXEC @hr = sp_OADestroy @dt
EXEC @hr = sp_OADestroy @bdTlv
EXEC @hr = sp_OADestroy @xmlSigned
EXEC @hr = sp_OADestroy @sbDigestValue
EXEC @hr = sp_OADestroy @sbSignatureValue
EXEC @hr = sp_OADestroy @cert
EXEC @hr = sp_OADestroy @bdPubKey
EXEC @hr = sp_OADestroy @bdCertSig
EXEC @hr = sp_OADestroy @xmlQR
EXEC @hr = sp_OADestroy @sbSignedXml
RETURN
END
DECLARE @sbReplaceStr int
EXEC @hr = sp_OACreate 'Chilkat.StringBuilder', @sbReplaceStr OUT
EXEC sp_OASetProperty @xmlQR, 'EmitXmlDecl', 0
EXEC sp_OASetProperty @xmlQR, 'EmitCompact', 1
EXEC sp_OAMethod @xmlQR, 'GetXml', @sTmp0 OUT
EXEC sp_OAMethod @sbReplaceStr, 'Append', @success OUT, @sTmp0
EXEC sp_OAMethod @sbReplaceStr, 'Append', @success OUT, '<cac:Signature>'
EXEC sp_OAMethod @sbReplaceStr, 'GetAsString', @sTmp0 OUT
EXEC sp_OAMethod @sbSignedXml, 'ReplaceFirst', @success OUT, '<cac:Signature>', @sTmp0
IF @success = 0
BEGIN
PRINT 'Did not find <cac:Signature> in the signed XML'
EXEC @hr = sp_OADestroy @dt
EXEC @hr = sp_OADestroy @bdTlv
EXEC @hr = sp_OADestroy @xmlSigned
EXEC @hr = sp_OADestroy @sbDigestValue
EXEC @hr = sp_OADestroy @sbSignatureValue
EXEC @hr = sp_OADestroy @cert
EXEC @hr = sp_OADestroy @bdPubKey
EXEC @hr = sp_OADestroy @bdCertSig
EXEC @hr = sp_OADestroy @xmlQR
EXEC @hr = sp_OADestroy @sbSignedXml
EXEC @hr = sp_OADestroy @sbReplaceStr
RETURN
END
-- Save the updated signed XML.
EXEC sp_OAMethod @sbSignedXml, 'WriteFile', @success OUT, 'qa_output/signedXML_withQR.xml', 'utf-8', 0
-- ----------------------------------------
-- Verify the updated signed XML to make sure we didn't invalidate the signature...
DECLARE @verifier int
EXEC @hr = sp_OACreate 'Chilkat.XmlDSig', @verifier OUT
EXEC sp_OAMethod @verifier, 'LoadSignatureSb', @success OUT, @sbSignedXml
IF @success <> 1
BEGIN
EXEC sp_OAGetProperty @verifier, 'LastErrorText', @sTmp0 OUT
PRINT @sTmp0
EXEC @hr = sp_OADestroy @dt
EXEC @hr = sp_OADestroy @bdTlv
EXEC @hr = sp_OADestroy @xmlSigned
EXEC @hr = sp_OADestroy @sbDigestValue
EXEC @hr = sp_OADestroy @sbSignatureValue
EXEC @hr = sp_OADestroy @cert
EXEC @hr = sp_OADestroy @bdPubKey
EXEC @hr = sp_OADestroy @bdCertSig
EXEC @hr = sp_OADestroy @xmlQR
EXEC @hr = sp_OADestroy @sbSignedXml
EXEC @hr = sp_OADestroy @sbReplaceStr
EXEC @hr = sp_OADestroy @verifier
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.
-- ----------------------------------------------------------------------------
EXEC sp_OASetProperty @verifier, 'UncommonOptions', 'ZATCA'
DECLARE @numSigs int
EXEC sp_OAGetProperty @verifier, 'NumSignatures', @numSigs OUT
DECLARE @verifyIdx int
SELECT @verifyIdx = 0
WHILE @verifyIdx < @numSigs
BEGIN
EXEC sp_OASetProperty @verifier, 'Selector', @verifyIdx
DECLARE @verified int
EXEC sp_OAMethod @verifier, 'VerifySignature', @verified OUT, 1
IF @verified <> 1
BEGIN
EXEC sp_OAGetProperty @verifier, 'LastErrorText', @sTmp0 OUT
PRINT @sTmp0
EXEC @hr = sp_OADestroy @dt
EXEC @hr = sp_OADestroy @bdTlv
EXEC @hr = sp_OADestroy @xmlSigned
EXEC @hr = sp_OADestroy @sbDigestValue
EXEC @hr = sp_OADestroy @sbSignatureValue
EXEC @hr = sp_OADestroy @cert
EXEC @hr = sp_OADestroy @bdPubKey
EXEC @hr = sp_OADestroy @bdCertSig
EXEC @hr = sp_OADestroy @xmlQR
EXEC @hr = sp_OADestroy @sbSignedXml
EXEC @hr = sp_OADestroy @sbReplaceStr
EXEC @hr = sp_OADestroy @verifier
RETURN
END
SELECT @verifyIdx = @verifyIdx + 1
END
PRINT 'All signatures were successfully verified.'
EXEC @hr = sp_OADestroy @dt
EXEC @hr = sp_OADestroy @bdTlv
EXEC @hr = sp_OADestroy @xmlSigned
EXEC @hr = sp_OADestroy @sbDigestValue
EXEC @hr = sp_OADestroy @sbSignatureValue
EXEC @hr = sp_OADestroy @cert
EXEC @hr = sp_OADestroy @bdPubKey
EXEC @hr = sp_OADestroy @bdCertSig
EXEC @hr = sp_OADestroy @xmlQR
EXEC @hr = sp_OADestroy @sbSignedXml
EXEC @hr = sp_OADestroy @sbReplaceStr
EXEC @hr = sp_OADestroy @verifier
END
GO