Sample code for 30+ languages & platforms
Zig

Sign Bolivia Invoice XML

See more XML Digital Signatures Examples

Demonstrates how to create an XML digital signature (XmlDSig) for a Bolivia invoice (factura).

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.

    // Create the following XML to be signed:

    // <?xml version="1.0" encoding="UTF-8"?>
    // <facturaElectronicaCompraVenta xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="facturaElectronicaCompraVenta.xsd">
    //     <cabecera>
    //         <nitEmisor>99999999</nitEmisor>
    //         <razonSocialEmisor>Abc Xyz</razonSocialEmisor>
    //         <municipio>Cochabamba - Cochabamba</municipio>
    //         <telefono>4444444</telefono>
    //         <numeroFactura>417</numeroFactura>
    //         <cuf>ABABABABABABABABABABABABABABABABABABABABABABABABABABABABA</cuf>
    //         <cufd>xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx</cufd>
    //         <codigoSucursal>0</codigoSucursal>
    //         <direccion>aaa aaa aaa</direccion>
    //         <codigoPuntoVenta>1</codigoPuntoVenta>
    //         <fechaEmision>2023-04-13T22:43:22.417</fechaEmision>
    //         <nombreRazonSocial>xyz</nombreRazonSocial>
    //         <codigoTipoDocumentoIdentidad>1</codigoTipoDocumentoIdentidad>
    //         <numeroDocumento>1234567</numeroDocumento>
    //            <complemento xsi:nil="true"/>
    //         <codigoCliente>1234567</codigoCliente>
    //         <codigoMetodoPago>1</codigoMetodoPago>
    //            <numeroTarjeta xsi:nil="true"/>
    //         <montoTotal>22.00</montoTotal>
    //         <montoTotalSujetoIva>22.00</montoTotalSujetoIva>
    //         <codigoMoneda>1</codigoMoneda>
    //         <tipoCambio>1.00</tipoCambio>
    //         <montoTotalMoneda>22.00</montoTotalMoneda>
    //            <montoGiftCard xsi:nil="true"/>
    //         <descuentoAdicional>0.00</descuentoAdicional>
    //            <codigoExcepcion>1</codigoExcepcion>
    //            <cafc xsi:nil="true"/>
    //         <leyenda>Ley N� 453: El proveedor de servicios debe habilitar medios e instrumentos para efectuar consultas y reclamaciones.</leyenda>
    //         <usuario>nromero</usuario>
    //         <codigoDocumentoSector>1</codigoDocumentoSector>
    //     </cabecera>
    //     <detalle>
    //         <actividadEconomica>620100</actividadEconomica>
    //         <codigoProductoSin>123456</codigoProductoSin>
    //         <codigoProducto>1</codigoProducto>
    //         <descripcion>Economicos</descripcion>
    //         <cantidad>1.00</cantidad>
    //         <unidadMedida>58</unidadMedida>
    //         <precioUnitario>22.00</precioUnitario>
    //         <montoDescuento>0.00</montoDescuento>
    //         <subTotal>22.00</subTotal>
    //            <numeroSerie xsi:nil="true"/>
    //            <numeroImei xsi:nil="true"/>
    //     </detalle>
    // </facturaElectronicaCompraVenta>

    // Use this online tool to generate code from sample XML:
    // Generate Code to Create XML

    const xml = try chilkat.Xml.init();
    defer xml.deinit();
    xml.setTag("facturaElectronicaCompraVenta");
    xml.addAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance") catch {};
    xml.addAttribute("xsi:noNamespaceSchemaLocation", "facturaElectronicaCompraVenta.xsd") catch {};
    xml.updateChildContent("cabecera|nitEmisor", "99999999");
    xml.updateChildContent("cabecera|razonSocialEmisor", "Abc Xyz");
    xml.updateChildContent("cabecera|municipio", "Cochabamba - Cochabamba");
    xml.updateChildContent("cabecera|telefono", "4444444");
    xml.updateChildContent("cabecera|numeroFactura", "417");
    xml.updateChildContent("cabecera|cuf", "ABABABABABABABABABABABABABABABABABABABABABABABABABABABABA");
    xml.updateChildContent("cabecera|cufd", "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
    xml.updateChildContent("cabecera|codigoSucursal", "0");
    xml.updateChildContent("cabecera|direccion", "aaa aaa aaa");
    xml.updateChildContent("cabecera|codigoPuntoVenta", "1");
    xml.updateChildContent("cabecera|fechaEmision", "2023-04-13T22:43:22.417");
    xml.updateChildContent("cabecera|nombreRazonSocial", "xyz");
    xml.updateChildContent("cabecera|codigoTipoDocumentoIdentidad", "1");
    xml.updateChildContent("cabecera|numeroDocumento", "1234567");
    xml.updateAttrAt("cabecera|complemento", true, "xsi:nil", "true") catch {};
    xml.updateChildContent("cabecera|codigoCliente", "1234567");
    xml.updateChildContent("cabecera|codigoMetodoPago", "1");
    xml.updateAttrAt("cabecera|numeroTarjeta", true, "xsi:nil", "true") catch {};
    xml.updateChildContent("cabecera|montoTotal", "22.00");
    xml.updateChildContent("cabecera|montoTotalSujetoIva", "22.00");
    xml.updateChildContent("cabecera|codigoMoneda", "1");
    xml.updateChildContent("cabecera|tipoCambio", "1.00");
    xml.updateChildContent("cabecera|montoTotalMoneda", "22.00");
    xml.updateAttrAt("cabecera|montoGiftCard", true, "xsi:nil", "true") catch {};
    xml.updateChildContent("cabecera|descuentoAdicional", "0.00");
    xml.updateChildContent("cabecera|codigoExcepcion", "1");
    xml.updateAttrAt("cabecera|cafc", true, "xsi:nil", "true") catch {};
    xml.updateChildContent("cabecera|leyenda", "Ley N� 453: El proveedor de servicios debe habilitar medios e instrumentos para efectuar consultas y reclamaciones.");
    xml.updateChildContent("cabecera|usuario", "nromero");
    xml.updateChildContent("cabecera|codigoDocumentoSector", "1");
    xml.updateChildContent("detalle|actividadEconomica", "620100");
    xml.updateChildContent("detalle|codigoProductoSin", "123456");
    xml.updateChildContent("detalle|codigoProducto", "1");
    xml.updateChildContent("detalle|descripcion", "Economicos");
    xml.updateChildContent("detalle|cantidad", "1.00");
    xml.updateChildContent("detalle|unidadMedida", "58");
    xml.updateChildContent("detalle|precioUnitario", "22.00");
    xml.updateChildContent("detalle|montoDescuento", "0.00");
    xml.updateChildContent("detalle|subTotal", "22.00");
    xml.updateAttrAt("detalle|numeroSerie", true, "xsi:nil", "true") catch {};
    xml.updateAttrAt("detalle|numeroImei", true, "xsi:nil", "true") catch {};

    const gen = try chilkat.XmlDSigGen.init();
    defer gen.deinit();

    gen.setSigLocation("facturaElectronicaCompraVenta");
    gen.setSigLocationMod(0);
    gen.setSigNamespacePrefix("");
    gen.setSigNamespaceUri("http://www.w3.org/2000/09/xmldsig#");
    gen.setSignedInfoCanonAlg("C14N");
    gen.setSignedInfoDigestMethod("sha256");

    gen.addSameDocRef("", "sha256", "C14N_WithComments", "", "") catch {};

    // Provide your certificate + private key. (PFX password is test123)
    const cert = try chilkat.Cert.init();
    defer cert.deinit();
    cert.loadPfxFile("qa_data/pfx/cert_test123.pfx", "test123") catch {
        std.debug.print("{s}\n", .{try cert.getLastErrorText(alloc)});
        return;
    };

    gen.setX509Cert(cert, true) catch {};

    gen.setKeyInfoType("X509Data");
    gen.setX509Type("Certificate");

    gen.setBehaviors("EnvelopedTransformFirst");

    // Load XML to be signed...
    const sb_xml = try chilkat.StringBuilder.init();
    defer sb_xml.deinit();
    xml.setEmitCompact(true);
    xml.getXmlSb(sb_xml) catch {};

    // Sign the XML...
    gen.createXmlDSigSb(sb_xml) catch {
        std.debug.print("{s}\n", .{try gen.getLastErrorText(alloc)});
        return;
    };

    // -----------------------------------------------

    // Save the signed XML to a file.
    try sb_xml.writeFile("qa_output/signedXml.xml", "utf-8", true);

    std.debug.print("{s}\n", .{try sb_xml.getAsString(alloc)});

    // ----------------------------------------
    // Verify the signatures we just produced...
    const verifier = try chilkat.XmlDSig.init();
    defer verifier.deinit();
    verifier.loadSignatureSb(sb_xml) catch {
        std.debug.print("{s}\n", .{try verifier.getLastErrorText(alloc)});
        return;
    };

    const num_sigs = verifier.getNumSignatures();
    var verify_idx: i32 = 0;
    while (verify_idx < num_sigs) {
        verifier.setSelector(verify_idx);
        verifier.verifySignature(true) catch {
            std.debug.print("{s}\n", .{try verifier.getLastErrorText(alloc)});
            return;
        };

        verify_idx = verify_idx + 1;
    }

    std.debug.print("All signatures were successfully verified.\n", .{});
}