Sample code for 30+ languages & platforms
Lua

Italian FatturaPA (e-Invoice) Signed XML (CADES-BES P7M) using USB SmartCard Reader

See more CAdES Examples

Demonstrates Italian e-Invoice (FatturaPA) signing by using a private key stored on a USB smartcard reader.

Chilkat Lua Downloads

Lua
local chilkat = require("chilkat")

-- This example assumes the Chilkat API to have been previously unlocked.
-- See Global Unlock Sample for sample code.

local crypt = chilkat.Crypt2.new()
crypt.verbose_logging = true

local cert = chilkat.Cert.new()
-- Use your smart card user PIN for signing.
cert.smart_card_pin = "0000"

local success = cert:load_from_smartcard("")
if not success then
    print(cert.last_error_text)
    return
end

success = crypt:set_signing_cert(cert)
if not success then
    print(crypt.last_error_text)
    return
end

-- The CadesEnabled property applies to all methods that create PKCS7 signatures.
-- To create a CAdES-BES signature, set this property equal to true.
crypt.cades_enabled = true

crypt.hash_algorithm = "sha256"

local signedAttrs = chilkat.JsonObject.new()
signedAttrs:update_int("contentType", 1)
signedAttrs:update_int("signingTime", 1)
signedAttrs:update_int("messageDigest", 1)
signedAttrs:update_int("signingCertificateV2", 1)
crypt.signing_attributes = signedAttrs:emit()

-- Load XML such as the following:
--  <p:FatturaElettronica xmlns:p="http://ivaservizi.agenziaentrate.gov.it/docs/xsd/fatture/v1.2" versione="FPR12">
--     <FatturaElettronicaHeader>
--        <DatiTrasmissione>
--     ...
--        </DatiTrasmissione>
--        <CedentePrestatore>
--     ...
--        </CedentePrestatore>
--        <CessionarioCommittente>
--     ...
--        </CessionarioCommittente>
--     </FatturaElettronicaHeader>
--     <FatturaElettronicaBody>
--        <DatiGenerali>
--           <DatiGeneraliDocumento>
--         ...
--           </DatiGeneraliDocumento>
--        </DatiGenerali>
--        <DatiBeniServizi>
--     ...
--        </DatiBeniServizi>
--     </FatturaElettronicaBody>
--  </p:FatturaElettronica>

local inputXmlPath = "c:/someDir/e-Invoice.xml"
local outputP7mPath = "c:/someDir/signed.p7m"

-- Create the CAdES-BES attached signature, which contains the original data.
success = crypt:create_p7_m(inputXmlPath, outputP7mPath)
if not success then
    print(crypt.last_error_text)
    return
end

print("Success.")