Sample code for 30+ languages & platforms
Rust Requires Chilkat v10.1.2+

Create PKCS7 Signed File (.p7m)

See more Encryption Examples

Demonstrates how to sign a file to create a .p7m that contains both the file contents and the signature.

Chilkat Rust Downloads

Rust

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

let crypt = chilkat::Crypt2::new();

let cert_store = chilkat::CertStore::new();

// Load a PFX file into a certificate store object.
if cert_store.load_pfx_file("myPfx.pfx", "pfxPassword").is_err() {
    println!("{}", cert_store.last_error_text());
    return;
}

// Get the certificate by subject common name.
// This should be the cert within the PFX that also
// has a private key (also stored within the PFX).
let json_cn = chilkat::JsonObject::new();
let _ = json_cn.update_string("CN", "myCert");
let cert = chilkat::Cert::new();
if cert_store.find_cert(&json_cn, &cert).is_err() {
    println!("{}", cert_store.last_error_text());
    return;
}

// Tell the crypt object to use the certificate for signing:
let _ = crypt.set_signing_cert(&cert).is_ok();

// Sign a file, producing a .p7m as output.
// The input file is unchanged, the test.p7m contains the 
// contents of the input file and the signature.
let in_file = "test.txt".to_string();
let out_file = "testp7m".to_string();
if crypt.create_p7_m(&in_file, &out_file).is_err() {
    println!("{}", crypt.last_error_text());
    return;
}

println!("Success!");