Rust
Rust
Sign a JWS with an HMAC Key
See more JSON Web Signatures (JWS) Examples
Demonstrates Jws.SetMacKey, which sets the symmetric MAC key for a signature. The key bytes are supplied in a named encoding such as hex or base64.
Background. HMAC-based JWS (for example HS256) authenticates the payload with a shared symmetric key that both signer and verifier possess.
Chilkat Rust Downloads
let jws = chilkat::Jws::new();
// Protected header specifying HMAC-SHA256.
let header = chilkat::JsonObject::new();
let _ = header.update_string("alg", "HS256");
if jws.set_protected_header(0, &header).is_err() {
println!("{}", jws.last_error_text());
return;
}
let b_include_bom = false;
if jws.set_payload("This is the content to sign.", "utf-8", b_include_bom).is_err() {
println!("{}", jws.last_error_text());
return;
}
// Set the symmetric MAC key for signature 0. The key bytes are provided in the named encoding (here
// base64). In production, obtain the key from a secure source rather than hard-coding it.
let base64_key = "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXowMTIzNDU=".to_string();
if jws.set_mac_key(0, &base64_key, "base64").is_err() {
println!("{}", jws.last_error_text());
return;
}
let Ok(jws_compact) = jws.create_jws() else {
println!("{}", jws.last_error_text());
return;
};
println!("{}", jws_compact);