Sample code for 30+ languages & platforms
Zig

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 Zig Downloads

Zig
const std = @import("std");
const chilkat = @import("chilkat");

pub fn main(init: std.process.Init) !void {
    const alloc = init.arena.allocator();

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

    const crypt = try chilkat.Crypt2.init();
    defer crypt.deinit();
    crypt.setVerboseLogging(true);

    const cert = try chilkat.Cert.init();
    defer cert.deinit();
    // Use your smart card user PIN for signing.
    cert.setSmartCardPin("0000");

    cert.loadFromSmartcard("") catch {
        std.debug.print("{s}\n", .{try cert.getLastErrorText(alloc)});
        return;
    };

    crypt.setSigningCert(cert) catch {
        std.debug.print("{s}\n", .{try crypt.getLastErrorText(alloc)});
        return;
    };

    // The CadesEnabled property applies to all methods that create PKCS7 signatures.
    // To create a CAdES-BES signature, set this property equal to true.
    crypt.setCadesEnabled(true);

    crypt.setHashAlgorithm("sha256");

    const signed_attrs = try chilkat.JsonObject.init();
    defer signed_attrs.deinit();
    signed_attrs.updateInt("contentType", 1) catch {};
    signed_attrs.updateInt("signingTime", 1) catch {};
    signed_attrs.updateInt("messageDigest", 1) catch {};
    signed_attrs.updateInt("signingCertificateV2", 1) catch {};
    crypt.setSigningAttributes(try signed_attrs.emit(alloc));

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

    const input_xml_path = "c:/someDir/e-Invoice.xml";
    const output_p7m_path = "c:/someDir/signed.p7m";

    // Create the CAdES-BES attached signature, which contains the original data.
    crypt.createP7M(input_xml_path, output_p7m_path) catch {
        std.debug.print("{s}\n", .{try crypt.getLastErrorText(alloc)});
        return;
    };

    std.debug.print("Success.\n", .{});
}