Sample code for 30+ languages & platforms
Rust

Validate a JWS with a Public Key

See more JSON Web Signatures (JWS) Examples

Demonstrates Jws.SetPublicKey, which sets the public key used to validate a signature of a loaded JWS.

The file path is relative to the application's current working directory. An absolute path may also be used. Supply the path appropriate to your own environment.

Background. The public key verifies a signature created with the corresponding private key. Validate returns 1 when valid, 0 when not, or a negative value on error.

Chilkat Rust Downloads

Rust

let jws = chilkat::Jws::new();

// Load the JWS compact serialization.
let jws_compact = "eyJhbGciOiJIUzI1NiJ9.VGhpcyBpcyB0aGUgY29udGVudCB0byBzaWduLg.<signature>".to_string();
if jws.load_jws(&jws_compact).is_err() {
    println!("{}", jws.last_error_text());
    return;
}

// The file path is relative to the application's current working directory.  An absolute path
// may also be used.  Supply the path appropriate to your own environment.
// Load the signer's public key and set it for validating signature 0.
let pub_key = chilkat::PublicKey::new();
if pub_key.load_from_file("qa_data/signer_pubkey.pem").is_err() {
    println!("{}", pub_key.last_error_text());
    return;
}

if jws.set_public_key(0, &pub_key).is_err() {
    println!("{}", jws.last_error_text());
    return;
}

// Validate the signature.  Validate returns 1 when valid, 0 when not, or a negative value on error.
let v = jws.validate(0);
if v < 0 {
    println!("{}", jws.last_error_text());
    return;
}

if v != 1 {
    println!("The signature is not valid.");
    return;
}

println!("The signature is valid.");