Sample code for 30+ languages & platforms
Rust

ScMinidriver - Import a Certificate and Private Key to a Smart Card or USB Token

See more ScMinidriver Examples

Demonstrates how to import a certificate and its private key to a key container on a smart card or USB token.

Note: This functionality was introduced in Chilkat v9.5.0.87.

Note: The ScMinidriver functionality is for Windows-only because ScMinidriver DLLs only exist on Windows.

Chilkat Rust Downloads

Rust

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

let scmd = chilkat::ScMinidriver::new();

// Reader names (smart card readers or USB tokens) can be discovered
// via List Readers or Find Smart Cards
let reader_name = "SCM Microsystems Inc. SCR33x USB Smart Card Reader 0".to_string();
if scmd.acquire_context(&reader_name).is_err() {
    println!("{}", scmd.last_error_text());
    return;
}

// If successful, the name of the currently inserted smart card is available:
println!("Card name: {}", scmd.card_name());

// To import a cert + private key, we'll need to be PIN authenticated.
// For more details about smart card PIN authentication, see the Smart Card PIN Authentication Example
let pin_id = "user".to_string();
let retval = scmd.pin_authenticate(&pin_id, "000000");
if retval != 0 {
    println!("PIN Authentication failed.");
    let _ = scmd.delete_context();
    return;
}

let cert = chilkat::Cert::new();

// Load the cert + private key from a .p12/.pfx
// We got this .p12 from https://badssl.com/download/
let password = "badssl.com".to_string();
if cert.load_pfx_file("qa_data/pfx/badssl.com-client.p12", &password).is_err() {
    println!("{}", cert.last_error_text());
    let _ = scmd.delete_context();
    return;
}

// Let's import this certificate as the "signature" key/cert in key container #6.
let container_index = 6;
let key_spec = "sig".to_string();
if scmd.import_cert(&cert, container_index, &key_spec, &pin_id).is_err() {
    println!("{}", scmd.last_error_text());
} else {
    println!("Successfully imported the cert + private key onto the smart card.");
}

// When finished with operations that required authentication, you may if you wish, deauthenticate the session.
if scmd.pin_deauthenticate("user").is_err() {
    println!("{}", scmd.last_error_text());
}

// Delete the context when finished with the card.
if scmd.delete_context().is_err() {
    println!("{}", scmd.last_error_text());
}