Sample code for 30+ languages & platforms
Rust Requires Chilkat v11.0.0+

Backup Windows Current User / Personal Certificates to a .zip

See more Certificates Examples

Demonstrates how to backup the certificates in the Windows registry-based Current User certificate store (in the "Personal" Logical Store as seen in certmgr.msc), to a zip archive. Certificates having an exportable private key are exported to .pfx files. Certificates with no private key, or with a non-exportable private key, are exported to .cer files.

Obviously, this example only runs on Windows computers.

Chilkat Rust Downloads

Rust
let mut success = false;

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

let read_only = true;
success = cert_store.open_current_user_store(read_only).is_ok();
if !success {
    println!("{}", cert_store.last_error_text());
    return;
}

let pfx_password = "secret".to_string();

let mut all_success = true;
let mut num_success = 0;

let zip = chilkat::Zip::new();
let _ = zip.new_zip("qa_output/personalCerts.zip");

let cert_data = chilkat::BinData::new();
let sb_filename = chilkat::StringBuilder::new();

// Iterate over the certificates in the Current User store.
let cert = chilkat::Cert::new();
let num_certs = cert_store.num_certificates();
let mut i = 0;
while i < num_certs {
    let _ = cert_store.get_cert(i, &cert);
    println!("DN = {}", cert.subject_dn());

    let _ = sb_filename.set_string("cert");
    let _ = sb_filename.append_int(i + 1);

    let b_has_private_key = cert.has_private_key();
    if (b_has_private_key) && (cert.private_key_exportable()) {
        // Export to a .pfx
        success = cert.export_to_pfx_bd(&pfx_password, true, &cert_data).is_ok();
        if success {
            let _ = sb_filename.append(".pfx");
            let _ = zip.add_bd(&sb_filename.get_as_string().unwrap_or_default(), &cert_data);
        }

    } else {
        // Export to a .cer
        success = cert.export_cert_der_bd(&cert_data).is_ok();
        if success {
            let _ = sb_filename.append(".cer");
            let _ = zip.add_bd(&sb_filename.get_as_string().unwrap_or_default(), &cert_data);
        }

    }

    if !success {
        all_success = false;
    } else {
        num_success = num_success + 1;
    }

    i = i + 1;
}

if num_success > 0 {
    if zip.write_zip_and_close().is_err() {
        println!("{}", zip.last_error_text());
        all_success = false;
    }

}

println!("All success = {}", all_success);