Rust Requires Chilkat v11.0.0+
Rust
RSA Sign with PKCS8 Encrypted Key
See more RSA Examples
Demonstrates how to load a private key from an encrypted PKCS8 file and create an RSA digital signature (and then verify it).Chilkat Rust Downloads
// This example assumes the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.
let priv_key = chilkat::PrivateKey::new();
// Load the private key from an RSA PEM file:
if priv_key.load_any_format_file("raul_privateKey.key", "a0123456789").is_err() {
println!("{}", priv_key.last_error_text());
return;
}
let rsa = chilkat::Rsa::new();
// Import the private key into the RSA component:
if rsa.use_private_key(&priv_key).is_err() {
println!("{}", rsa.last_error_text());
return;
}
// This example will sign a string, and receive the signature
// in a hex-encoded string. Therefore, set the encoding mode
// to "hex":
rsa.set_encoding_mode("hex");
let str_data = "This is the string to be signed.".to_string();
// Sign the string using the sha256 hash algorithm.
// Other valid choices are sha1, sha384, sha512 and others.
let Ok(hex_sig) = rsa.sign_string_enc(&str_data, "sha256") else {
println!("{}", rsa.last_error_text());
return;
};
println!("{}", hex_sig);
// Now verify with the public key.
// This example shows how to use the public key from
// a digital certificate (.cer file)
let cert = chilkat::Cert::new();
if cert.load_from_file("raul_publicKey.cer").is_err() {
println!("{}", cert.last_error_text());
return;
}
let pub_key = chilkat::PublicKey::new();
let _ = cert.get_public_key(&pub_key);
let rsa2 = chilkat::Rsa::new();
if rsa2.use_public_key(&pub_key).is_err() {
println!("{}", rsa2.last_error_text());
return;
}
// Verify the signature against the original data:
rsa2.set_encoding_mode("hex");
if rsa2.verify_string_enc(&str_data, "sha256", &hex_sig).is_err() {
println!("{}", rsa2.last_error_text());
return;
}
println!("Signature verified!");
// Verify with incorrect data:
if rsa2.verify_string_enc("something else", "sha256", &hex_sig).is_err() {
println!("Signature not verified! (which was expected in this case)");
} else {
println!("Hmmm... that's not right...");
}