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

Generate RSA Key and Sign a String

See more RSA Examples

Demonstrates how to generate a new RSA public/private key pair and use it to generate a signature for a string. The (binary) digital signature is returned as a hexidecimalized string.

Chilkat Rust Downloads

Rust

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

let rsa = chilkat::Rsa::new();

// Generate a 2048-bit RSA key.
let priv_key = chilkat::PrivateKey::new();
let _ = rsa.gen_key(2048, &priv_key).is_ok();

let _ = rsa.use_private_key(&priv_key);

// Return the signature in hex.
rsa.set_encoding_mode("hex");

let str_data = "This is the string to be signed.".to_string();

// Sign the SHA256 hash of the string.
let hex_sig = rsa.sign_string_enc(&str_data, "sha256").unwrap_or_default();

println!("{}", hex_sig);

// Now verify the signature:
let pub_key = chilkat::PublicKey::new();
let _ = priv_key.to_public_key(&pub_key);
let _ = rsa.use_public_key(&pub_key);

if rsa.verify_string_enc(&str_data, "sha256", &hex_sig).is_ok() {
    println!("Signature verified!");
} else {
    println!("{}", rsa.last_error_text());
}

// Try it with an invalid signature:
if rsa.verify_string_enc(&str_data, "sha256", "not a valid sig").is_ok() {
    println!("Signature verified!");
} else {
    println!("Signature validation failed!");
}

// Try it with invalid data:
if rsa.verify_string_enc("Not the original data", "sha256", &hex_sig).is_ok() {
    println!("Signature verified!");
} else {
    println!("Signature validation failed!");
}