Sample code for 30+ languages & platforms
Rust

JWE using A256GCMKW

See more JSON Web Encryption (JWE) Examples

This example demonstrates creating a JCE with AES GCM key wrap.

Chilkat Rust Downloads

Rust

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

let plaintext = "My text to enrypt".to_string();

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

// First build the JWE Protected Header: 

//         {
//             "alg": "A256GCMKW",
//             "kid": "18ec08e1-bfa9-4d95-b205-2b4dd1d4321d",
//             "tag": "kfPduVQ3T3H6vnewt--ksw",
//             "iv": "KkYT0GX_2jHlfqN_",
//             "enc": "A128CBC-HS256"
//         }

let jwe_prot_hdr = chilkat::JsonObject::new();
let _ = jwe_prot_hdr.append_string("alg", "A256GCMKW");
// kid is optional
let _ = jwe_prot_hdr.append_string("kid", "18ec08e1-bfa9-4d95-b205-2b4dd1d4321d");
// tag is optional
let _ = jwe_prot_hdr.append_string("tag", "kfPduVQ3T3H6vnewt--ksw");
let _ = jwe_prot_hdr.append_string("enc", "A256GCM");
// the iv should be 16 random chars.
let prng = chilkat::Prng::new();
let _ = jwe_prot_hdr.append_string("iv", &prng.random_string(16, true, true, true).unwrap_or_default());
let _ = jwe.set_protected_header(&jwe_prot_hdr);

println!("JWE Protected Header: {}", jwe_prot_hdr.emit().unwrap_or_default());
println!("--");

// Given that we have 256-bit AES, our key should be 32 bytes.
// The ascii string here is 32 bytes, therefore the 2nd arg is "ascii" to use these
// ascii chars directly as the key.
let aes_wrapping_key = "2baf4f730f5e4542b428593ef9cceb0e".to_string();
let _ = jwe.set_wrapping_key(0, &aes_wrapping_key, "ascii");

// Encrypt and return the JWE:
let Ok(str_jwe) = jwe.encrypt(&plaintext, "utf-8") else {
    println!("{}", jwe.last_error_text());
    return;
};

// Show the JWE we just created:
println!("{}", str_jwe);

// Decrypt the JWE that was just produced.
// 1) Load the JWE.
// 2) Set the AES wrapping key.
// 3) Decrypt.
let jwe2 = chilkat::Jwe::new();
if jwe2.load_jwe(&str_jwe).is_err() {
    println!("{}", jwe2.last_error_text());
    return;
}

// Set the AES wrap key.  Important to use "ascii"
let _ = jwe2.set_wrapping_key(0, &aes_wrapping_key, "ascii");

// Decrypt.
let Ok(original_plaintext) = jwe2.decrypt(0, "utf-8") else {
    println!("{}", jwe2.last_error_text());
    return;
};

println!("original text: ");
println!("{}", original_plaintext);