Sample code for 30+ languages & platforms
Rust

Import an SSH Key to an HSM using PKCS11

See more PKCS11 Examples

Demonstrates how to import an SSH private key to an HSM (smartcard or token).

Note: This example requires Chilkat v9.5.0.96 or later.

Chilkat Rust Downloads

Rust

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

// Note: Chilkat's PKCS11 implementation runs on Windows, Linux, Mac OS X, and other supported operating systems.

let pkcs11 = chilkat::Pkcs11::new();

// Use the PKCS11 driver (.dll, .so, .dylib) for your particular HSM.
// For example:
pkcs11.set_shared_lib_path("C:/Program Files (x86)/Gemalto/IDGo 800 PKCS#11/IDPrimePKCS11.dll");

// Use your HSM's PIN.
let pin = "0000".to_string();

// Normal user = 1
let user_type = 1;

// Establish a logged-on user session with the HSM.
if pkcs11.quick_session(user_type, &pin).is_err() {
    println!("{}", pkcs11.last_error_text());
    return;
}

// Create a PKCS11 template for importing the SSH key.
let json_template = chilkat::JsonObject::new();

// Indicate the key is to be stored on the token (i.e. it is not a session-only key)
let _ = json_template.update_bool("token", true);
// The key should have the ability to sign
let _ = json_template.update_bool("sign", true);

// Let's provide a few attributes to help us find the this key at a later time.
// See SSH Public-Key Authentication using an HSM

// The ID is byte data, so it should be base64 or hex.
// Specify "id" if passing base64 data, "id_hex" for hexidecimal, or "id_ascii" for directly copying the ascii bytes of the string.
// You can provide any ID of your choice.  It is optional.
let _ = json_template.update_string("id_hex", "0A0B0C0D01020304");

// Optionally specify a label.
let _ = json_template.update_string("label", "MySshKey");

// Load the SSH key to be imported to the HSM (smartcard or token)
let ssh_key = chilkat::SshKey::new();
ssh_key.set_password("password_of_the_encrypted_ppk_file");
let ppk_contents = ssh_key.load_text("c:/my_ssh_keys/someSshKey.ppk").unwrap_or_default();
if ssh_key.from_putty_private_key(&ppk_contents).is_err() {
    println!("{}", ssh_key.last_error_text());
    return;
}

// Import the SSH private key onto the HSM.
// The PKCS11 handle to the imported private key is returned.
// A 0 is returned on failure.
let priv_key_handle = pkcs11.import_ssh_key(&ssh_key, &json_template);
if priv_key_handle == 0 {
    println!("{}", pkcs11.last_error_text());
    return;
}

// The private key handle is only valid during the PKCS11 session.
// If you wish to use the private key in another PKCS11 session,
// you'll first need to find it.  See  SSH Public-Key Authentication using a Smartcard
println!("private key handle: {}", priv_key_handle);

println!("Successfully imported the SSH key onto the HSM.");

let _ = pkcs11.logout();
let _ = pkcs11.close_session();