Rust
Rust
JWE using ECDH-ES, BP-256, A256GCM
See more JSON Web Encryption (JWE) Examples
Create a JWE with the following header:
{
"alg": "ECDH-ES",
"enc": "A256GCM",
"exp": 1621957030,
"cty": "NJWT",
"epk": {
"kty": "EC",
"x": "QLpJ_LpFx-6yJhsb4OvHwU1khLnviiOwYOvmf5clK7w"
"y": "AJh7pJ3zZKDJkm8rbeG69GBooTosXJgSsvNFH0i3Vxnu"
"crv": "BP-256"
}
}
Note: This example requires Chilkat v9.5.0.87 or greater.
Chilkat Rust Downloads
// This requires the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.
// Load our brainpool BP-256 public key.
// {
// "use": "enc",
// "kid": "puk_idp_enc",
// "kty": "EC",
// "crv": "BP-256",
// "x": "QLpJ_LpFx-6yJhsb4OvHwU1khLnviiOwYOvmf5clK7w",
// "y": "AJh7pJ3zZKDJkm8rbeG69GBooTosXJgSsvNFH0i3Vxnu"
// }
let json = chilkat::JsonObject::new();
let _ = json.update_string("use", "enc");
let _ = json.update_string("kid", "puk_idp_enc");
let _ = json.update_string("kty", "EC");
let _ = json.update_string("crv", "BP-256");
let _ = json.update_string("x", "QLpJ_LpFx-6yJhsb4OvHwU1khLnviiOwYOvmf5clK7w");
let _ = json.update_string("y", "AJh7pJ3zZKDJkm8rbeG69GBooTosXJgSsvNFH0i3Vxnu");
let pubkey = chilkat::PublicKey::new();
if pubkey.load_from_string(&json.emit().unwrap_or_default()).is_err() {
println!("{}", pubkey.last_error_text());
return;
}
// Build our protected header:
// {
// "alg": "ECDH-ES",
// "enc": "A256GCM",
// "exp": 1621957030,
// "cty": "NJWT",
// "epk": {
// "kty": "EC",
// "x": "QLpJ_LpFx-6yJhsb4OvHwU1khLnviiOwYOvmf5clK7w"
// "y": "AJh7pJ3zZKDJkm8rbeG69GBooTosXJgSsvNFH0i3Vxnu"
// "crv": "BP-256"
// }
// }
// Use jwt only for getting the current date/time + 3600 seconds.
let jwt = chilkat::Jwt::new();
let jwe_prot_hdr = chilkat::JsonObject::new();
let _ = jwe_prot_hdr.update_string("alg", "ECDH-ES");
let _ = jwe_prot_hdr.update_string("enc", "A256GCM");
let _ = jwe_prot_hdr.update_int("exp", jwt.gen_numeric_date(3600));
let _ = jwe_prot_hdr.update_string("cty", "NJWT");
let _ = jwe_prot_hdr.update_string("epk.kty", "EC");
let _ = jwe_prot_hdr.update_string("epk.x", "QLpJ_LpFx-6yJhsb4OvHwU1khLnviiOwYOvmf5clK7w");
let _ = jwe_prot_hdr.update_string("epk.y", "AJh7pJ3zZKDJkm8rbeG69GBooTosXJgSsvNFH0i3Vxnu");
let _ = jwe_prot_hdr.update_string("epk.crv", "BP-256");
let jwe = chilkat::Jwe::new();
let _ = jwe.set_protected_header(&jwe_prot_hdr);
let _ = jwe.set_public_key(0, &pubkey);
let plain_text = "This is the text to be encrypted.".to_string();
let Ok(str_jwe) = jwe.encrypt(&plain_text, "utf-8") else {
println!("{}", jwe.last_error_text());
return;
};
println!("{}", str_jwe);
println!("Success.");