Rust Requires Chilkat v11.0.0+
Rust
RSA Signature/Verify with .key and .cer
See more RSA Examples
Demonstrates how to use a .key file (private key) and digital certificate (.cer, public key) to create and verify an RSA signature.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 .key file:
if priv_key.load_pem_file("privateKey.key").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;
}
// Create the signature as a hex string:
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 "md2", "sha1", "sha384",
// "sha512", and "md5".
let hex_sig = rsa.sign_string_enc(&str_data, "sha256").unwrap_or_default();
println!("{}", hex_sig);
// Load a digital certificate from a .cer file:
let cert = chilkat::Cert::new();
if cert.load_from_file("myCert.cer").is_err() {
println!("{}", cert.last_error_text());
return;
}
let pub_key = chilkat::PublicKey::new();
let _ = cert.get_public_key(&pub_key);
// Now verify using a new instance of the RSA object:
let rsa2 = chilkat::Rsa::new();
// Import the public key into the RSA object:
if rsa2.use_public_key(&pub_key).is_err() {
println!("{}", rsa2.last_error_text());
return;
}
// The signature is a hex string, so make sure the EncodingMode is correct:
rsa2.set_encoding_mode("hex");
// Verify the signature:
if rsa2.verify_string_enc(&str_data, "sha256", &hex_sig).is_err() {
println!("{}", rsa2.last_error_text());
return;
}
println!("Success.");