Sample code for 30+ languages & platforms
Rust

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

Rust

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

let crypt = chilkat::Crypt2::new();
crypt.set_verbose_logging(true);

let cert = chilkat::Cert::new();
// Use your smart card user PIN for signing.
cert.set_smart_card_pin("0000");

if cert.load_from_smartcard("").is_err() {
    println!("{}", cert.last_error_text());
    return;
}

if crypt.set_signing_cert(&cert).is_err() {
    println!("{}", crypt.last_error_text());
    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.set_cades_enabled(true);

crypt.set_hash_algorithm("sha256");

let signed_attrs = chilkat::JsonObject::new();
let _ = signed_attrs.update_int("contentType", 1);
let _ = signed_attrs.update_int("signingTime", 1);
let _ = signed_attrs.update_int("messageDigest", 1);
let _ = signed_attrs.update_int("signingCertificateV2", 1);
crypt.set_signing_attributes(&signed_attrs.emit().unwrap_or_default());

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

let input_xml_path = "c:/someDir/e-Invoice.xml".to_string();
let output_p7m_path = "c:/someDir/signed.p7m".to_string();

// Create the CAdES-BES attached signature, which contains the original data.
if crypt.create_p7_m(&input_xml_path, &output_p7m_path).is_err() {
    println!("{}", crypt.last_error_text());
    return;
}

println!("Success.");