Sample code for 30+ languages & platforms
Rust

ECDSA Sign and Verify Data using Different Hash Algorithms

See more ECC Examples

Demonstrates how to create ECDSA signatures on data using different hash algorithms.

Note: This example requires Chilkat v9.5.0.85 or greater because the SignBd and VerifyBd methods were added in v9.5.0.85.

Chilkat Rust Downloads

Rust

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

// First load an ECDSA private key to be used for signing.
let priv_key = chilkat::PrivateKey::new();
if priv_key.load_encrypted_pem_file("qa_data/ecc/secp256r1-key-pkcs8-secret.pem", "secret").is_err() {
    println!("{}", priv_key.last_error_text());
    return;
}

// Load some data to be signed.
let bd = chilkat::BinData::new();
if bd.load_file("qa_data/hamlet.xml").is_err() {
    println!("Failed to load file to be hashed.");
    return;
}

let ecdsa = chilkat::Ecc::new();
let prng = chilkat::Prng::new();

// Sign the sha256 hash of the data.  Return the ECDSA signature in the base64 encoding.
println!("ECDSA signing the sha256 hash of the data...");
let mut sig = ecdsa.sign_bd(&bd, "sha256", "base64", &priv_key, &prng).unwrap_or_default();
println!("sig = {}", sig);

// Verify the signature against the original data.
// (We must use the same hash algorithm that was used when signing.)

// Load the public key that corresponds to the private key used for signing.
let pub_key = chilkat::PublicKey::new();
if pub_key.load_from_file("qa_data/ecc/secp256r1-pub.pem").is_err() {
    println!("{}", pub_key.last_error_text());
    return;
}

let ecc2 = chilkat::Ecc::new();
let mut result = ecc2.verify_bd(&bd, "sha256", &sig, "base64", &pub_key);
if result != 1 {
    println!("{}", ecc2.last_error_text());
    return;
}

println!("Verified!");

// ----------------------------------------------------------------------------------------
// Let's do the same thing, but with sha384 hashing...

println!("--------------------------------------------");
println!("ECDSA signing the sha384 hash of the data...");

sig = ecdsa.sign_bd(&bd, "sha384", "base64", &priv_key, &prng).unwrap_or_default();
println!("sig = {}", sig);

result = ecc2.verify_bd(&bd, "sha384", &sig, "base64", &pub_key);
if result != 1 {
    println!("{}", ecc2.last_error_text());
    return;
}

println!("Verified!");