Rust
Rust
JWE with Binary Data
See more JSON Web Encryption (JWE) Examples
Demonstrates how to create a JWE that contains a binary payload (such as a JPG image).Note: This example requires Chilkat v9.5.0.66 or greater.
Chilkat Rust Downloads
let mut success = false;
// This requires the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.
// Note: This example requires Chilkat v9.5.0.66 or greater.
// Load a JPG file that will be the JWE payload.
let jpg_bytes = chilkat::BinData::new();
success = jpg_bytes.load_file("qa_data/jpg/starfish.jpg").is_ok();
// Make sure your app checks the success/failure of the call to LoadFile..
println!("Original JPG size = {}", jpg_bytes.num_bytes());
let jwe = chilkat::Jwe::new();
let jwe_prot_hdr = chilkat::JsonObject::new();
let _ = jwe_prot_hdr.append_string("alg", "A128KW");
let _ = jwe_prot_hdr.append_string("enc", "A128CBC-HS256");
let _ = jwe.set_protected_header(&jwe_prot_hdr);
let aes_wrapping_key = "GawgguFyGrWKav7AX4VKUg".to_string();
let _ = jwe.set_wrapping_key(0, &aes_wrapping_key, "base64url");
// Encrypt and return the JWE in sbJwe:
let sb_jwe = chilkat::StringBuilder::new();
success = jwe.encrypt_bd(&jpg_bytes, &sb_jwe).is_ok();
if !success {
println!("{}", jwe.last_error_text());
return;
}
// Show the JWE:
println!("{}", sb_jwe.get_as_string().unwrap_or_default());
println!("size of JWE: {}", sb_jwe.length());
// ---------------------------------------------------------
// Decrypt to get the original JPG file..
let jwe2 = chilkat::Jwe::new();
success = jwe2.load_jwe_sb(&sb_jwe).is_ok();
if !success {
println!("{}", jwe2.last_error_text());
return;
}
// Set the AES wrap key.
let _ = jwe2.set_wrapping_key(0, &aes_wrapping_key, "base64url");
// Decrypt.
let jpg_original = chilkat::BinData::new();
success = jwe2.decrypt_bd(0, &jpg_original).is_ok();
if !success {
println!("{}", jwe2.last_error_text());
return;
}
println!("Decrypted JPG size = {}", jpg_original.num_bytes());
// Save the decrypted JPG to a file.
success = jpg_original.write_file("qa_output/jwe_decrypted_starfish.jpg").is_ok();
println!("success = {}", success);
// The output of this program, when tested, was:
// Original JPG size = 6229
// eyJhbGciOiJBMTI4S1ciLCJlbmMiOiJBMTI4Q0JDLUhTMjU2In0.9YFz_wteV ... 7Et3hKhpxnKEXw
// size of JWE: 8473
// Decrypted JPG size = 6229
// success = True