Rust Requires Chilkat v10.1.3+
Rust
Yubikey RSA Encrypt/Decrypt
See more RSA Examples
Demonstrates how to do RSA decryption using a private key stored on a Yubikey (or other USB token or smartcard).Note: RSA encryption uses the public key, which is freely exportable and does not need to occur on the token/smartcard.
Chilkat Rust Downloads
// This example assumes you have a certificate with private key on the Yubikey token.
// When doing simple RSA encryption/decryption, we don't actually need the certificate,
// but we'll be using the private key associated with the certificate.
//
// The sensitive/secret material that needs to be kept private is the private key.
// The certificate itself and the public key can be freely shared.
//
// We're going to encrypt and decrypt 32-bytes of data.
let bd = chilkat::BinData::new();
let _ = bd.append_encoded("000102030405060708090A0B0C0D0E0F", "hex").is_ok();
let _ = bd.append_encoded("000102030405060708090A0B0C0D0E0F", "hex").is_ok();
// Let's get the desired cert.
// For this example, a self-signed certificate with a 2048-bit RSA key was generated in slot 9A.
let cert = chilkat::Cert::new();
// Force Chilkat to use PKCS11 over ScMinidriver (if on Windows) and Apple Keychain (if on MacOS)
cert.set_uncommon_options("NoScMinidriver,NoAppleKeychain");
cert.set_smart_card_pin("123456");
if cert.load_from_smartcard("cn=chilkat_test_2048").is_err() {
println!("{}", cert.last_error_text());
return;
}
// RSA encrypt using the public key.
let rsa = chilkat::Rsa::new();
// Provide the RSA object with the certificate on the Yubkey.
if rsa.set_x509_cert(&cert, true).is_err() {
println!("{}", rsa.last_error_text());
return;
}
// RSA encrypt using the public key.
let mut use_private_key = false;
if rsa.encrypt_bd(&bd, use_private_key).is_err() {
println!("{}", rsa.last_error_text());
return;
}
println!("RSA Encrypted Output in Hex:");
println!("{}", bd.get_encoded("hex").unwrap_or_default());
// Now let's decrypt, using the private key on the Yubikey.
use_private_key = true;
if rsa.decrypt_bd(&bd, use_private_key).is_err() {
println!("{}", rsa.last_error_text());
return;
}
println!("RSA Decrypted Output in Hex:");
println!("{}", bd.get_encoded("hex").unwrap_or_default());