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

RSA Sign Binary Data and Verify (Recover the Original Data)

See more RSA Examples

Demonstrates how to RSA sign binary data and then verify/recover the original data.

Note: This example uses methods introduced in Chilkat v9.5.0.77.

Chilkat Rust Downloads

Rust

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

// Load an RSA private key for signing.
let priv_key = chilkat::PrivateKey::new();
if priv_key.load_encrypted_pem_file("qa_data/pem/rsa_passwd.pem", "passwd").is_err() {
    println!("{}", priv_key.last_error_text());
    return;
}

let rsa = chilkat::Rsa::new();
let _ = rsa.use_private_key(&priv_key);

// We have some binary data (in hex) to sign
let original_data = "0102030405060708090A".to_string();
let bd = chilkat::BinData::new();
let _ = bd.append_encoded(&original_data, "hex");

// If successful, the contents of bd are replaced with the RSA signature.
if rsa.sign_raw_bd(&bd).is_err() {
    println!("{}", rsa.last_error_text());
    return;
}

// Show the RSA signature in base64
println!("{}", bd.get_encoded("base64").unwrap_or_default());

// ------------------------------------------
// Get the public key from the private key
let pub_key = chilkat::PublicKey::new();
let _ = priv_key.to_public_key(&pub_key);

// Verify the signature and extract the original data.
let rsa2 = chilkat::Rsa::new();
let _ = rsa2.use_public_key(&pub_key);

let b_verified = rsa2.verify_raw_bd(&bd).is_ok();
println!("signature verified: {}", b_verified);

// Show the original data:
println!("original data: {}", bd.get_encoded("hex").unwrap_or_default());