Sample code for 30+ languages & platforms
Rust

Decrypt a JWE with a Private Key

See more JSON Web Encryption (JWE) Examples

Demonstrates Jwe.SetPrivateKey, which sets the private key used to decrypt a recipient of a loaded JWE.

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 private key unwraps the content-encryption key that was wrapped with the corresponding public key during encryption.

Chilkat Rust Downloads

Rust

let jwe = chilkat::Jwe::new();

// Load the JWE compact serialization to be decrypted.
let jwe_compact = "eyJhbGciOiJBMjU2S1ciLCJlbmMiOiJBMjU2R0NNIn0.<...>.<iv>.<ciphertext>.<tag>".to_string();
if jwe.load_jwe(&jwe_compact).is_err() {
    println!("{}", jwe.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 recipient's private key.
let priv_key = chilkat::PrivateKey::new();
if priv_key.load_pem_file("qa_data/recipient_privkey.pem").is_err() {
    println!("{}", priv_key.last_error_text());
    return;
}

// Set the private key used to decrypt recipient 0.
if jwe.set_private_key(0, &priv_key).is_err() {
    println!("{}", jwe.last_error_text());
    return;
}

let Ok(content) = jwe.decrypt(0, "utf-8") else {
    println!("{}", jwe.last_error_text());
    return;
};

println!("{}", content);